0

I'am trying to develop a nodejs service that will work as a proxy between my apis and third party apis. What I need to implement is a system capable of receiving multiple api responses and "translate" the response to an object with the keys my backend is expecting. For example:

I have a resource name "cars". My api is expecting the following object:

{ 
  name: 'car1',
  type: 'suv',
  date: '24-12-1998'
}

But the third party api responds with an object like this one:

{
  label: 'car1',
  firstRecord: '24-12-1998',
  segment: 'suv'
}

What I need, is a way to map the fields and "translate" the object to what i am expecting and do this in a way that is scalable to multiple third party apis.

What are your thoughts on this?

  • Does this answer your question? [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – GrafiCode Feb 10 '20 at 09:58

1 Answers1

2

You can create an object and a function to map keys

const keyMappings = {
  label: 'name',
  firstRecord: 'date',
  segment: 'type'
}

const obj = {label: 'car1', firstRecord: '24-12-1998', segment: 'suv', nonExisting: 'foo'}


const translate = (obj) => {

  return Object.keys(obj).reduce((acc, key) => {
    const newKey = keyMappings[key] ? keyMappings[key] : key
    acc[newKey] = obj[key]
    return acc;
  }, {})

}

const translatedObj = translate(obj);

console.log(translatedObj);
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Yes. This was the approach I was thinking about using. Other thing I came up with was the use of Typescript interfaces. What do you think about that? – Bruno Ramos Feb 10 '20 at 10:06
  • You can use interfaces as well but you will still need to map the keys. Maybe I can help you further if you share an example of what you mean by using interfaces. – Harun Yilmaz Feb 10 '20 at 10:10