Skip to content

Instantly share code, notes, and snippets.

@B4nan
Created February 6, 2022 17:44
Show Gist options
  • Save B4nan/d567527b6d07a9cf7e4b4abc073e0ca9 to your computer and use it in GitHub Desktop.
Save B4nan/d567527b6d07a9cf7e4b4abc073e0ca9 to your computer and use it in GitHub Desktop.
const god = em.create(Author, {
name: 'God', // validates required properties
email: 'god@heaven.io',
books: [{
title: 'Bible, part 1',
tags: [{ name: 'old' }, { name: 'bestseller' }],
}],
}, { persist: true }); // we can enable this globally via `persistOnCreate: true`
await em.flush();
// simulate new request
em.clear();
// `authors` is of type `Loaded<Author, 'books.tags'>[]`
const authors = await em.find(Author, {}, {
populate: ['books.tags'], // populate hint can be inferred from `fields` if not explicitly provided
fields: ['books.tags.name'], // strict partial loading with dot notation support
orderBy: { name: 'asc', books: { tags: { name: 'asc' } } }, // strict order by with object nesting
});
// `books` and `tags` will be typed as `LoadedCollection` so we can use safe `$` accessor
console.log(authors[0].books.$[0].tags.$[0].name);
const dto = wrap(authors[0]).toObject();
console.log(dto.books[0].tags[0].name); // DTOs are also strictly typed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment