Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Embedded Objects vs Embedded Types in Archetype
const Archetype = require('archetype');
const assert = require('assert');
const RequestType = new Archetype({
service: {
$type: 'string',
$required: true
},
// `location` is implicitly `$required` because
// `type` and `coordinates` are `$required`
// Can use a custom type for `PointType`, and
// usually you should, but you don't have to
location: {
type: {
$type: 'string',
$required: true,
$default: 'Point',
$validate: v => assert.strictEqual(v, 'Point', `Invalid type ${v}`)
},
coordinates: {
// Coordinates is an array of numbers
$type: ['number'],
$required: true,
$validate: v => assert.equal(v.length, 2, `Must have 2 coordinates`)
}
}
}).compile('RequestType');
const r = new RequestType({
service: 'Coffee Delivery',
location: {
// Near Northern California
coordinates: [-122, 37]
}
});
// Note that below, `location` is **not** an instance of PointType,
// it is just a POJO
// RequestType {
// service: 'Coffee Delivery',
// location: { coordinates: [ -122, 37 ], type: 'Point' } }
console.log(r);
// 'Point'
console.log(r.location.type);
const Archetype = require('archetype');
const assert = require('assert');
const PointType = new Archetype({
type: {
$type: 'string',
$required: true,
$default: 'Point',
$validate: v => assert.strictEqual(v, 'Point', `Invalid type ${v}`)
},
coordinates: {
// Coordinates is an array of numbers
$type: ['number'],
$required: true,
$validate: v => assert.equal(v.length, 2, `Must have 2 coordinates`)
}
}).compile('PointType');
const RequestType = new Archetype({
service: {
$type: 'string',
$required: true
},
// Perfectly valid, archetypes can be embedded in other archetypes
// Must be `$required` though, the fact that `type` is `$required`
// for `PointType` does **not** bubble up to making `location.type`
// `$required` for `RequestType`.
location: {
$type: PointType,
$required: true
}
}).compile('RequestType');
const r = new RequestType({
service: 'Coffee Delivery',
location: {
// Near Northern California
coordinates: [-122, 37]
}
});
// RequestType {
// service: 'Coffee Delivery',
// location: PointType { coordinates: [ -122, 37 ], type: 'Point' } }
console.log(r);
// true
console.log(r.location instanceof PointType);
// 'Point'
console.log(r.location.type);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.