Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created November 24, 2017 19:45
Show Gist options
  • Save vkarpov15/37622608b33eb144acfda5d3ad936be6 to your computer and use it in GitHub Desktop.
Save vkarpov15/37622608b33eb144acfda5d3ad936be6 to your computer and use it in GitHub Desktop.
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