Home Reference Source
import Model from 'autonym/lib/Model'
public class | source

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

async create(data: Record, meta: Meta, hookArgs: array): Promise<Record, AutonymError>

Creates a new record.

public

async find(query: object, meta: Meta, hookArgs: array): Promise<Record[], AutonymError>

Finds records.

public

async findOne(id: string, meta: Meta, hookArgs: array): Promise<Record, AutonymError>

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

async init(): Promise<*, Error>

Initializes the model if it hasn't been already.

public

Serializes the data for a store method.

public

Unserializes the data from a store method.

public

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:

NameTypeAttributeDescription
config object

Configuration.

config.name string

A unique name for the model, like 'user'.

config.init function(): * | Promise<*, Error>
  • optional

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 null to disable schema validation.

config.optionalUpdateProperties Array<string|string[]>
  • optional

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
  • optional

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[]>
  • optional

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
  • optional

Configuration policies.

config.store Store

Configuration store.

config.route string
  • optional

The route to use for requests of this type of record. Defaults to pluralizing the name property and then converting it to kebab-case.

config.initialMeta Meta
  • optional

The initial value of the meta object that is passed to the policies and store methods.

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.

Params:

NameTypeAttributeDescription
data Record

The properties of the record to create.

meta Meta
  • optional

Additional metadata to pass to the store.

hookArgs array
  • optional

Used internally. Arguments to pass into the hooks.

Return:

Promise<Record, AutonymError>

The new record data.

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.

Params:

NameTypeAttributeDescription
query object
  • optional

The query to filter by.

meta Meta
  • optional

Additional metadata to pass to the store.

hookArgs array
  • optional

Used internally. Arguments to pass into the hooks.

Return:

Promise<Record[], AutonymError>

The data of the found 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.

Params:

NameTypeAttributeDescription
id string

The id of the record to find.

meta Meta
  • optional

Additional metadata to pass to the store.

hookArgs array
  • optional

Used internally. Arguments to pass into the hooks.

Return:

Promise<Record, AutonymError>

The found record data.

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.

Params:

NameTypeAttributeDescription
id string

The id of the record to delete.

meta Meta
  • optional

Additional metadata to pass to the store.

hookArgs array
  • optional

Used internally. Arguments to pass into the hooks.

Return:

Promise<object, AutonymError>

An object containing an id property set to the deleted record's id.

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:

NameTypeAttributeDescription
id string

The id of the record to update.

data Record

The properties to update.

completeData Record
  • optional

The complete record with the properties to update merged in. If omitted, it will be fetched.

meta Meta
  • optional

Additional metadata to pass to the store.

hookArgs array
  • optional

Used internally. Arguments to pass into the hooks.

Return:

Promise<Record, AutonymError>

The updated record data.

Example:

const data = await Post.findOneAndUpdate('1', { title: 'Test' })

console.log(data) // { id: '1', title: 'Test', body: 'This is my first post.' }

public getConfig(): object source

Gets the normalized config.

Return:

object

The normalized config.

public getInitialMeta(): Meta source

Gets the initial meta.

Return:

Meta

The initial meta.

public getName(): string source

Gets the model name.

Return:

string

The model name.

public getPolicies(): ModelPolicies source

Gets the policies.

Return:

ModelPolicies

The policies.

public getRoute(): string source

Gets the model route.

Return:

string

The model route.

public async init(): Promise<*, Error> source

Initializes the model if it hasn't been already.

Return:

Promise<*, Error>

The result of the initialization.

public async serialize(data: Record): Promise<SerializedRecord, AutonymError> source

Serializes the data for a store method.

Params:

NameTypeAttributeDescription
data Record

The data to serialize.

Return:

Promise<SerializedRecord, AutonymError>

The serialized data.

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:

NameTypeAttributeDescription
data SerializedRecord

The data to unserialize.

Return:

Promise<Record, AutonymError>

The unserialized data.

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.

Params:

NameTypeAttributeDescription
data Record

The data to validate. This must be a complete record.

method string
  • optional

One of 'create', 'find', 'findOne', 'findOneAndUpdate', or 'findOneAndDelete', which may determine different schema restrictions based on the configuration.

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' }

public withHooks(hooks: object): Model source

Used internally. Creates a copy of the model instance with the given lifecycle hooks added to it.

Params:

NameTypeAttributeDescription
hooks object

A set of lifecycle hooks.

Return:

Model

A copy of the model instance with the given hooks installed.