Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Embedding Only Certain Fields in an Embedded Archetype
const Archetype = require('archetype');
const UserType = new Archetype({
name: { $type: 'string', $required: true },
age: { $type: 'number', $required: true }
}).compile('UserType');
const RequestType = new Archetype({
createdAt: { $type: Date },
user: {
// Embed only the `name` property from the user. Will copy
// the `$required` over as well.
$type: UserType.pick(['name']).compile('RequestUserType')
}
}).compile('RequestType');
// UserType { name: 'Val', age: 29 }
console.log(new UserType({ name: 'Val', age: 29 }));
// Since we only picked one property, `name`, from user, this works.
// `user.age` is **not** required
// Prints: RequestType { user: RequestUserType { name: 'Test' } }
console.log(new RequestType({
user: { name: 'Test' }
}));
// Since `age` is not in the embedded `user` property, it
// will get stripped out.
// Prints: RequestType { user: RequestUserType { name: 'Test' } }
console.log(new RequestType({
user: { name: 'Test', age: 29 }
}));
// Will throw an error
// Prints: user: name: Path "name" is required
console.log(new RequestType({
user: {}
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment