Creating Entities

To create or retrieve an entity, you can call the factory static method of an entity's class and pass in an optional GUID. You can also use the factorySync method if you need to create a new entity synchronously. The benefit of using the factory methods is that they can return the correct type in TypeScript. To check that an entity hasn't been saved yet, check that the GUID is null (entity.guid == null).

// BlogPost extends the Entity class.
let blogPost = await BlogPost.factory();

// Check that the entity is new.
if (someBlogPost.guid == null) {
  alert("This blog post hasn't been saved yet!");
}

Much like entries in many blogging systems, entities can be organized using tags. The tags provide a fast way to query entities.

blogPost.$addTag('super-post');
await blogPost.$save();

let superPosts = await nymph.getEntities(
  { class: BlogPost },
  { type: '&', tag: 'super-post' }
);

blogPost.$inArray(superPosts); // true

Be cautious when saving an entity in another entity's property. If the referenced entity is newly created and does not have a GUID, Nymph will not be able to retrieve it later. Always save the referenced entity first.

Saving a Referenced Entity the Right Way
let entity = await Entity.factory();
entity.foo = await Entity.factory();

entity.foo.bar = 'It works!';
await entity.foo.$save(); // Saving the referenced entity first! :)
await entity.$save(); // now foo has been saved.

const guid = entity.guid;
entity = await Entity.factory(guid);

entity.foo.guid == null; // False
console.log(entity.foo.bar); // Outputs 'It works!'.
Saving a Referenced Entity the Wrong Way
let entity = await Entity.factory();
entity.foo = await Entity.factory();

await entity.$save(); // foo hasn't been saved yet!

entity.foo.bar = 'It works!';
await entity.foo.$save();

const guid = entity.guid;
entity = await Entity.factory(guid);

entity.foo.guid == null; // True
console.log(entity.foo.bar); // Outputs undefined.

Caution: Since the referenced entity's class name is stored in the reference on the parent entity, if you change the class name in an update, you need to reassign all referenced entities of that class and resave.

When an entity is loaded, it does not request its referenced entities from Nymph. Instead, it creates instances without data called "sleeping references". You can use `$wake` on the entity or `$wakeAll` on the parent entity to get the entity's data from the DB. The $wakeAll method will awaken all sleeping references in the entity's data. You can call $clearCache in Node.js or $refresh in the client to turn all the entities back into sleeping references.

Previous: Introduction Next: Entity Querying