Model
Class that defines an entity type for a record accessible in your API.
Constructor Summary
Public Constructor | ||
public |
constructor(config: object, A: function(ajv: Ajv): *) |
Method Summary
Public Methods | ||
public |
Creates a new record. |
|
public |
Finds records. |
|
public |
Finds a record. |
|
public |
async findOneAndDelete(id: string, meta: Meta, hookArgs: array): Promise<object, AutonymError> Deletes a record. |
|
public |
async findOneAndUpdate(id: string, data: Record, completeData: Record, meta: Meta, hookArgs: array): Promise<Record, AutonymError> Updates a record. |
|
public |
Gets the normalized config. |
|
public |
Gets the initial meta. |
|
public |
Gets the model name. |
|
public |
Gets the policies. |
|
public |
Gets the model route. |
|
public |
Initializes the model if it hasn't been already. |
|
public |
async serialize(data: Record): Promise<SerializedRecord, AutonymError> Serializes the data for a store method. |
|
public |
async unserialize(data: SerializedRecord): Promise<Record, AutonymError> Unserializes the data from a store method. |
|
public |
async validateAgainstSchema(data: Record, method: string): Promise<Record, AutonymError> Validates the data against the schema. |
|
public |
Used internally. Creates a copy of the model instance with the given lifecycle hooks added to it. |
Public Constructors
public constructor(config: object, A: function(ajv: Ajv): *) source
Params:
Name | Type | Attribute | Description |
config | object | Configuration. |
|
config.name | string | A unique name for the model, like |
|
config.init | function(): * | Promise<*, Error> |
|
A function to call when the model is first used. |
config.schema | Schema | null | A JSON schema to validate data against before passing it to the store
methods, or explicitly |
|
config.optionalUpdateProperties | Array<string|string[]> |
|
A list of properties that are normally required in the schema but may be optional in a findOneAndUpdate request. This is rarely needed as request data is merged with the existing record before schema validation occurs, but this can be helpful when properties are converted to computed properties when saved (e.g. user records that have a passwordHash property and whose password is deleted). |
config.ajvOptions | AjvOptions |
|
Additional options to pass to the Ajv instance. |
A | function(ajv: Ajv): * | function called when the Ajv object is instantiated. It is passed the Ajv instance for hooking in custom keywords, etc. |
|
config.computedProperties | Array<string|string[]> |
|
A list of properties that do not appear on the schema but should still be passed to the store methods. These properties cannot be part of the request body since they are stripped during schema validation, but they may be set by policies. |
config.policies | ModelPolicies |
|
Configuration policies. |
config.store | Store | Configuration store. |
|
config.route | string |
|
The route to use for requests of this type of record. Defaults to pluralizing
the |
config.initialMeta | Meta |
|
The initial value of the |
Example:
const Post = new Model({
name: 'post',
init: Db.connect(),
schema: {
type: 'object',
properties: {
title: { type: 'string' },
body: { type: 'string' },
},
require: ['title', 'body'],
},
policies: {
create: {
preSchema: { and: [getCurrentUserPolicy, canCreatePostPolicy] },
postSchema: trimPostBodyPolicy,
},
find: {
postStore: addTotalCountHeaderToResponsePolicy,
},
findOneAndUpdate: {
preSchema: { and: [getCurrentUserPolicy, userIsOwnerOfPostPolicy] },
postSchema: trimPostBodyPolicy,
},
findOneAndDelete: {
preStore: { and: [getCurrentUserPolicy, userIsOwnerOfPostPolicy] },
},
},
store: {
create: data => Db.insert('posts', data),
find: () => Db.selectAll('posts'),
findOne: id => Db.selectOne('posts', { id }),
findOneAndUpdate: (id, data) => Db.updateWhere('posts', { id }, data),
findOneAndDelete: id => Db.deleteWhere('posts', { id }),
serialize: data => mapKeys(data, property => snakeCase(property)),
unserialize: data => mapKeys(data, columnName => camelCase(columnName)),
},
})
Public Methods
public async create(data: Record, meta: Meta, hookArgs: array): Promise<Record, AutonymError> source
Creates a new record.
Example:
const data = await Post.create({
title: 'Hello World',
body: 'This is my first post.',
})
console.log(data) // { id: '1', title: 'Hello World', body: 'This is my first post.' }
public async find(query: object, meta: Meta, hookArgs: array): Promise<Record[], AutonymError> source
Finds records.
Example:
const data = await Post.find()
console.log(data) // [{ id: '1', title: 'Hello World', body: 'This is my first post.' }]
public async findOne(id: string, meta: Meta, hookArgs: array): Promise<Record, AutonymError> source
Finds a record.
Example:
const data = await Post.findOne('1')
console.log(data) // { id: '1', title: 'Hello World', body: 'This is my first post.' }
public async findOneAndDelete(id: string, meta: Meta, hookArgs: array): Promise<object, AutonymError> source
Deletes a record.
Return:
Promise<object, AutonymError> | An object containing an |
Example:
const data = await Post.findOneAndDelete('1')
console.log(data) // { id: '1' }
public async findOneAndUpdate(id: string, data: Record, completeData: Record, meta: Meta, hookArgs: array): Promise<Record, AutonymError> source
Updates a record.
Params:
Name | Type | Attribute | Description |
id | string | The id of the record to update. |
|
data | Record | The properties to update. |
|
completeData | Record |
|
The complete record with the properties to update merged in. If omitted, it will be fetched. |
meta | Meta |
|
Additional metadata to pass to the store. |
hookArgs | array |
|
Used internally. Arguments to pass into the hooks. |
Example:
const data = await Post.findOneAndUpdate('1', { title: 'Test' })
console.log(data) // { id: '1', title: 'Test', body: 'This is my first post.' }
public async serialize(data: Record): Promise<SerializedRecord, AutonymError> source
Serializes the data for a store method.
Params:
Name | Type | Attribute | Description |
data | Record | The data to serialize. |
Example:
const data = await Post.serialize({ authorId: '42' })
console.log(data) // { author_id: '42' }
public async unserialize(data: SerializedRecord): Promise<Record, AutonymError> source
Unserializes the data from a store method.
Params:
Name | Type | Attribute | Description |
data | SerializedRecord | The data to unserialize. |
Example:
const data = await Post.unserialize({ author_id: '42' })
console.log(data) // { authorId: '42' }
public async validateAgainstSchema(data: Record, method: string): Promise<Record, AutonymError> source
Validates the data against the schema.
Return:
Promise<Record, AutonymError> | Resolves with the validated data, which has unrecognized properties filtered out and default values added. |
Example:
const validatedData = await Post.validateAgainstSchema({ title: 'Hello World', xyz: 123 })
console.log(validatedData) // { title: 'Hello World' }