I’m currently writing a "converter" for importing and exporting data.
The specific data are vehicles.
So basically I’m getting a vehicle from a supplier let’s say like so
{
"id": 1234,
"category": "CAR",
"warranty": {
"warranty_begin": "tomorrow",
"warranty_end": "the day after tomorrow"
}
// And so on
}
And on an import I will map it to a json format reasonable for our api like:
{
"internal_id": 1234,
"category": "CAR",
"warranty": {
"warranty_start_date": "tomorrow",
"warranty_end_date": "the day after tomorrow"
}
// And so on
}
This is pretty easy to write you just access the keys you need and map the values to your keys.
Exactly the same thing can be done for an export where we map our data to the suppliers format.
But
I’m right now looking for method to do it in a two way function manner. I imagine myself something like this.
On import
fromPathTo("id", "internalId");
fromPathTo("category", "category");
// And so on
run();
On export
fromPathTo("id", "internalId");
fromPathTo("category", "category");
// And so on
runInverse();
Where run Inverse then flips the parameters there should also be a way to write functions like:
convertWithFn(originPath: string, converter: Function, destinationPath: string)
convertWithEnum(originPath: string, enum: Array<Array<string> | string>, destinationPath: string)
And things like that
I’m pretty sure there might be a way to do it I just can’t find it. Does someone of you have an idea?
2
Answers
The following code gives a rough idea, but it makes some simplifications. For example, it assumes that property names are unique across levels and thereby avoids things like
fromPathTo("warranty/warranty_begin", "warranty/warranty_start_date")
. And it would have to be extended to support mapping functions likeconvertWithFn
.Yes, there is a way, but careful if you rely on others making this work you’ll be in trouble when inevitably something goes wrong and you have to debug this beast.
So my suggestion would be to use a simpler non generic solution, like:
Sidenote: I’ve removed the nested
warranty
object in on of the models to demonstrate a maping/change of the structure of the objects, not just the property names.Nonetheless here the promised converter:
The other thing is, I’m not sure how to properly type this converter. The two functions in the first snippet (
convert()
andconvertBack()
) are basically self explanatory, even for the TS compiler. I even manage to make thelens()
function typesafe, but deriving a model from a set of paths (not keynames) is beyond my (current) abilities. Keep that in mind when using solutions like this one.