Add from function to initialize a model and assign properties values using any object, silently ignoring fields which are not properties.
All checks were successful
/ test (push) Successful in 51s

This commit is contained in:
Madeorsk 2025-04-20 20:45:52 +02:00
parent fbd2763ea6
commit 7707789bbf
Signed by: Madeorsk
GPG key ID: 677E51CA765BB79F
3 changed files with 45 additions and 0 deletions

View file

@ -286,6 +286,18 @@ const alteredModelInstance = definedModel.model(modelInstance).assign({
});
```
#### `from(object)`
Initialize a model instance and assign the provided fields to its properties. Fields which are not properties of the target model are silently ignored.
```typescript
const newModelInstance = definedModel.from({
anyProperty: "foo",
anotherOne: true,
not_a_property: "will be ignored",
});
```
#### `serialize()`
Serialize the model.

View file

@ -460,6 +460,16 @@ export class ModelManager<T extends object, Shape extends ModelShape<T>, Identif
return (new Model<T, Shape, Identifier>(this)).initInstance();
}
/**
* Initialize a new model instance with the provided object properties values.
* Fields that cannot be matched to existing properties are silently ignored.
* @param fields
*/
from(fields: Partial<ModelPropertiesValues<T, Shape>> & {[field: string]: any}): ModelInstance<T, Shape, Identifier>
{
return this.model().assign(fields);
}
/**
* Parse the serialized model object to a new model instance.
* @param serialized The serialized model object.

View file

@ -356,4 +356,27 @@ describe("model", () => {
text: "fully new text! yes!",
});
});
it("initializes a model from properties values", () => {
const testArticle = Article.model.from({
title: "this is a test",
authors: [
Account.model.from({ name: "John Doe", email: "test@test.test", createdAt: new Date(), active: true }),
],
text: "this is a long text",
evaluation: 8.52,
tags: [{ name: "test" }, { name: "foo" }],
unknownField: true,
anotherOne: "test",
});
expect(testArticle.title).toBe("this is a test");
expect(testArticle.text).toBe("this is a long text");
expect(testArticle.evaluation).toBe(8.52);
expect(testArticle.authors).toHaveLength(1);
expect(testArticle.authors[0]?.name).toBe("John Doe");
expect((testArticle as any).unknownField).toBeUndefined();
expect((testArticle as any).anotherOne).toBeUndefined();
});
});