From 7707789bbf2584fd2a75503e57049b981bb5121f Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Sun, 20 Apr 2025 20:45:52 +0200 Subject: [PATCH] Add from function to initialize a model and assign properties values using any object, silently ignoring fields which are not properties. --- README.md | 12 ++++++++++++ src/model/model.ts | 10 ++++++++++ tests/model.test.ts | 23 +++++++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/README.md b/README.md index 4bd104e..8488517 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/model/model.ts b/src/model/model.ts index c676e46..b253973 100644 --- a/src/model/model.ts +++ b/src/model/model.ts @@ -460,6 +460,16 @@ export class ModelManager, Identif return (new Model(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> & {[field: string]: any}): ModelInstance + { + return this.model().assign(fields); + } + /** * Parse the serialized model object to a new model instance. * @param serialized The serialized model object. diff --git a/tests/model.test.ts b/tests/model.test.ts index ef3f34b..bc5416c 100644 --- a/tests/model.test.ts +++ b/tests/model.test.ts @@ -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(); + }); });