A
A
Artur Galyaev2022-03-05 16:00:24
JavaScript
Artur Galyaev, 2022-03-05 16:00:24

How to make a data schema (model) from an object received from the server?

Hello, the following object comes from the server:

{
  id: 1,
  test_service_id: 43,
  data: {
    title: "test",
    img: null
  },
  user_info: {
    name: "test"
  }
}

I need to normalize this object like this:
{
  id: 1,
  testServiceId: 43,
  title: "test".
  img: null,
  userInfo: {
    name: "test"
  }
}

What is the best way to do this?

Alternatively, you can create a model class and then, when sent to the server, assemble it again.
class Model {
  constructor(raw) {
    this.id = id
    this.testServiceId = raw.test_service_id
    ...
  }
}


How do you organize objects coming from the server, what solutions/approaches do you use for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Pautov, 2022-03-05
@art5455

That's exactly what to do. 2 models ModelInput for input and ModelOutput for output.
You can also read about BFF, but this is an extreme case, but it solves such issues.
But in general, it is desirable to agree on a name with the backend. Otherwise, in my opinion, this is mostly "garbage" code that does nothing, but only inflates it with an empty rename.
Try to explain to them that you guys are working with json natirovaniya, it does not oblige you to anything, but still.
That I, for example, have linters that do not allow writing properties with underscores, dashes.
Or, I have to write them like this: obj['my_prop']which is not very good.
To summarize:
1) Agree, explain why this is bad for you and what problems it causes. And what problems can you get from it.
2) Make your models for renaming
3) BFF
4) Hammer in a bolt if this is a passing project.
PS I am convinced that json must be in camelCase nattion. In my projects, I have repeatedly urged backend teams to do this. But these were all new projects. If the project is already old, then there’s definitely nothing to do here, or BFF.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question