2.6 KiB
2.6 KiB
archetype
![](https://i.imgur.com/TW4rq2f.png)
Archetype is a library for casting and validating objects. It has exceptional support for deeply nested objects, type composition, custom types, and geoJSON.
const { ObjectId } = require('mongodb');
const moment = require('moment');
// `Person` is now a constructor
const Person = new Archetype({
name: 'string',
bandId: {
$type: ObjectId,
$required: true
},
createdAt: {
$type: moment,
$default: () => moment()
}
}).compile('Person');
const test = new Person({
name: 'test',
bandId: '507f191e810c19729de860ea'
});
test.bandId; // Now a mongodb ObjectId
test.createdAt; // moment representing now
If casting fails, archetype throws a nice clean exception:
try {
new Person({
name: 'test',
bandId: 'ImNotAValidObjectId'
});
} catch(error) {
error.errors['bandId'].message; // Mongodb ObjectId error
}
Archetypes are composable, inspectable, and extendable via extends
.
Connect
Follow archetype on Twitter for updates, including our gists of the week. Here's some older gists of the week:
- 20180112: Virtual Types with Archetype
- 20180105: Transform an Archetype So All Properties are Not Required
- 20171124: Embedding Only Certain Fields in an Embedded Archetype
- 20171117: Async/Await with Archetype
- 20171110: Configuring Custom Validators for Individual Paths in Archetype
- 20171103: Conditionally Required Properties with Archetype
- 20171027: Custom Types with Archetype
- 20171020: Embedding a Subset of One Archetype's Properties in another Archetype
- 20171013: Embedded Objects vs Embedded Types in Archetype
- 20171006: Consistent Arrays from Query Params with Express and Archetype