Skip to content

Conversation

@akphi
Copy link
Owner

@akphi akphi commented Apr 25, 2023

When I specify the model schema for 2 classes where one extends the other, the order of fields during serialization of the subclass sometimes do not follow the order specified in in createModelSchema. Look at the example I provided

import { createModelSchema, primitive, serialize } from "serializr";

class Person {
  name;
}

class Worker extends Person {
  company;
}

// 1.
// const workerModelSchema = createModelSchema(Worker, {
//   company: primitive(),
//   name: primitive(),
// });
//
// output: { company: 'FirmX', name: 'John' } --> this works

const personModelSchema = createModelSchema(Person, {
  name: primitive(),
});

// 2.
const workerModelSchema = createModelSchema(Worker, {
  company: primitive(),
  name: primitive(),
});
//
// output: { name: 'John', company: 'FirmX' } --> this doesn't work as expected

// 3.
// const workerModelSchema2 = {
//   factory: () => new Worker(),
//   props: {
//     company: primitive(),
//     name: primitive(),
//   },
// };
//
// output: { company: 'FirmX', name: 'John' } --> this works

const newWorker = new Worker();
newWorker.name = "John";
newWorker.company = "FirmX";

const json = serialize(workerModelSchema, newWorker);

console.log(json);

I have 2 classes Person and Worker extends Person. When using createModelSchema, if I specify the model schema for Person before I specify the model schema for Worker, when I try to serialize an instance of Worker, the props in the model schema of Worker which overlap with the props in the model schema of Person will always be arranged first, and the fields which specialized to Worker will be arranged last, in the example, I'm trying to serialize using workerModelSchema, which specifies company field to go before name, but in the output, I don't see this.

Now, if I use the (1), where I specify the model schema of Worker before I do Person, I would get what I expected, or if I do (3) where I avoid using createModelSchema, I would get what I expected as well.

I really think this is a bug due to the inconsistency we see here, I suppose this has to do with some intricate handling we do in createModelSchema

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants