Перейти к основному содержимому

API

DataProvider

Methods

  • registerConnection(name: string): void - Register connection in your data storage
    • name - name of connection
  • dump(): SerializedStorage - Get all data from your data provider
  • restore(data: SerializedStorage): void - Set data to data provider
    • data - - data to set
  • registerModule(path: ModulePath, initialState?: State): void - Register module in your connection
    • path - tuple like [connection, <moduleName>]
    • initialState - optional initial module state
  • getModuleState(module: ModulePath): State - Get state of specific module
    • module - tuple like [connection, <moduleName>]
  • hasModule(module: ModulePath): boolean - Does specific module exist
    • module - tuple like [connection, <moduleName>]
  • save(module: ModulePath, records: Elements): void - Save data
    • module - tuple like [connection, <moduleName>]
    • records - record like { [id: string]: Entity }
  • insert(module: ModulePath, records: Elements): void - Insert data
    • module - tuple like [connection, <moduleName>]
    • records - record like { [id: string]: Entity }
  • replace(module: ModulePath, records: Elements): void - Replace part of data with new data
    • module - tuple like [connection, <moduleName>]
    • records - record like { [id: string]: Entity }
  • update(module: ModulePath, records: Elements): void - Update part of data
    • module - tuple like [connection, <moduleName>]
    • records - record like { [id: string]: Entity }
  • delete(module: ModulePath, ids: string[]): void - Delete data
    • module - tuple like [connection, <moduleName>]
    • ids - primaryKey array of elements which will be deleted
  • flush(module: ModulePath): void - Remove all data from module
    • module - tuple like [connection, <moduleName>]

Database

Methods

  • isStarted() - Whether the database has already been installed or not. The model registration procedure depends on this flag.
  • getRepository<R extends Repository<InstanceType<M>>, M extends typeof Model = typeof Model>(model: M): R - Get repository for model
    • model - model for which a repository is needed
  • registerCustomRepository<R extends Repository>(repo: Constructor<R>): this - Add custom repository constructor
    • repo - constructor of your repository
  • setDataProvider(dataProvider: DataProvider): this - Set data provider
    • dataProvider - instance of chosen DataProvider
  • getDataProvider() - Get current database DataProvider. Returns initial DataProvider, not wrapped with EventsDataProviderWrapper.
  • getWrappedDataProvider() - Get current DataProvider wrapped in EventsDataProviderWraper
  • setConnection(connection: string): this - Set the connection.
    • connection - connection name
  • getConnection(): string - Get current database connection
  • start(): this - Initialize the database before a user can start using it.
  • register<M extends Model>(model: M): void - Register the given model.
    • model - model to register
  • getModel<M extends Model>(name: string): M - Get a model by the specified entity name.
    • name - model name (from static entity field)
  • getSchema(name: string): EntitySchema - Get schema by the specified entity name.
    • name - model name (from static entity field)
  • on(event: Extract<RattusEvent, 'save' | 'insert' | 'update' | 'replace'>, callback: DataEventCallback<Elements, Elements>): CancelSubscriptionCallback - Listen to RattusEvent which can modify data it operates with. Should return an updated data.
    • event - event to listen to
    • callback - callback, accepts Elements, returns Elements
  • on(event: typeof RattusEvents.DELETE, callback: DataEventCallback<string[], string[]>): CancelSubscriptionCallback - Listen to RattusEvent on delete data. Should return an array of primary keys that will be deleted
    • event - event to listen to
    • callback - callback, accepts Array<string | number>, returns Array<string | number>
  • on(event: typeof RattusEvents.MODULE_REGISTER, callback: DataEventCallback<ModuleRegisterEventPayload, ModuleRegisterEventPayload>): CancelSubscriptionCallback - Listen to RattusEvent on register new module. Should return special metadata payload: { path: ModulePath, initialState?: State }
    • event - event to listen to
    • callback - callback, accepts ModuleRegisterEventPayload, returns ModuleRegisterEventPayload
  • on(event: typeof RattusEvents.FLUSH, callback: DataEventCallback<undefined>): CancelSubscriptionCallback - Listen to RattusEvent on flush data. Can't modify data.
    • event - event to listen to
    • callback - void callback
  • on(event: typeof RattusEvents.CONNECTION_REGISTER, callback: DataEventCallback<string>): CancelSubscriptionCallback - Listen to RattusEvent on connection register. Can't modify data.
    • event - event to listen to
    • callback - void callback, accepts connection name.
  • on(event: typeof RattusEvents.DATA_CHANGED, callback: DataEventCallback<DataChangedEventPayload>): CancelSubscriptionCallback - Listen to RattusEvent on any data changed. Can't modify data.
    • event - event to listen to
    • callback - void callback, accepts { path: ModulePath, state: State }
  • resetListeners(event?: RattusEvent) - Reset listeners for specific event
    • event - reset for this event
  • use(plugin: DatabasePlugin): this - Use plugin
    • plugin - database plugin function
  • dump(): SerializedStorage - Export all data from current connection as JavaScript object
  • restore(data: SerializedStorage) - Import data into database
    • data - data to import

Model

Properties

  • static entity: string - The name of the model.
  • static dataTypeCasting: boolean = true - Should or should not cast data types
  • static primaryKey: string | string[] = 'id' - The primary key for the model.

Methods

  • static fields(): ModelFields - Create a new model fields definition.
  • static setRegistry<M extends typeof Model>(key: string, attribute: () => Attribute<unknown>): M - Set the attribute to the registry.
    • key - model field name
    • attribute - attribute factory
  • static clearBootedModels(): void - Clear the list of booted models, so they can be re-booted.
  • static clearRegistries(): void - Clear registries.
  • static newRawInstance<M extends Model>(): M - Create a new model instance without field values being populated. This method is mainly for the internal use when registering models to the database. Since all pre-registered models are for referencing its model setting during the various process, but the fields are not required. Use this method when you want create a new model instance for: - Registering model to a component (eg. Repository, Query, etc.) - Registering model to attributes (String, Has Many, etc.)
  • $self(): typeof Model - Get the constructor for this model.
  • $entity(): string - Get the entity for this model.
  • $primaryKey(): string | string[] - Get the primary key for this model.
  • $fields(): ModelFields - Get the model fields for this model.
  • $newInstance(attributes?: Element, options?: ModelOptions): this - Create a new instance of this model. This method provides a convenient way to re-generate a fresh instance of this model. It's particularly useful during hydration through Query operations.
    • attributes - data to fill new instance with
    • options - options (should fill, include relations)
  • $fill(attributes: Element = {}, options: ModelOptions = {}): this - Fill this model by the given attributes. Missing fields will be populated by the attributes default value.
    • attributes - data to fill new instance with
    • options - options (should fill, include relations)
  • $getKeyName(): string | string[] - Get the primary key field name.
  • $getKey(record: Element = this): string | number | (string | number)[] | null - Get primary key value for the model. If the model has the composite key, it will return an array of ids.
    • record - optional data of element to get key
  • $getIndexId(record: Element = this): string - Get the index id of this model or for a given record.
    • record - optional data of element to index id
  • $getLocalKey(): string - Get the local key name for the model.
  • $getRelation(name: string): Relation - Get the relation instance for the given relation name.
    • name - name of relation to get instance
  • $setRelation(relation: string, model: Model | Model[] | null): this - Set the given relationship on the model.
    • relation - relation name
    • model - model to set relation
  • $getAttributes(): Element - Get the serialized model attributes.
  • $toJson(options: ModelOptions = { relations: true }): RawModel<this> - Serialize this model, or the given model, as POJO.
    • options - optional options to apply
  • $sanitize(record: Element): Element - Sanitize the given record. This method is similar to `$toJson` method, but the difference is that it doesn't instantiate the full model. The method is used to sanitize the record before persisting to the store. It removes fields that don't exist in the model field schema or if the field is relationship fields. Note that this method only sanitizes existing fields in the given record. It will not generate missing model fields. If you need to generate all model fields, use `$sanitizeAndFill` method instead.
    • record - data to sanitize
  • $sanitizeAndFill(record: Element): Element - Same as `$sanitize` method, but it produces missing model fields with its default value.
    • record - data to sanitize
  • getThisNonStrict() -

Query

Methods

  • constructor(protected readonly database: Database, model: M, eagerLoad: EagerLoad = {}, skip: number = 0, take: number | null = null, orders: Order[] = [], wheres: Where[] = []) - Create a new query instance.
    • database - database to work with
    • model - model to work with
    • eagerLoad - the relationships that should be eager loaded, default {}
    • skip - the number of records to skip, default 0
    • take - the maximum number of records to return, default null
    • orders - the orderings for the query, default []
    • wheres - the where constraints for the query, default []
  • newQuery(model: string): Query<Model> - Create a new query instance for the given model.
    • model - model entity to work with
  • newQueryWithConstraints(model: string): Query<Model> - Create a new query instance with constraints for the given model.
    • model - model entity to work with
  • newQueryForRelation(relation: Relation): Query<Model> - Create a new query instance from the given relation.
    • relation - relation to get model from
  • where(field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any): this - Add a basic where clause to the query.
    • field - field name to work with
    • value - optional value to match
  • whereIn(field: string, values: any[]): this - Add a "where in" clause to the query.
    • field - field name to work with
    • values - values to match
  • whereId(ids: string | number | (string | number)[]): this - Add a where clause on the primary key to the query.
    • ids - primary keys to match
  • orWhere(field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any): this - Add an "or where" clause to the query.
    • field - field name to work with
    • value - optional value to match
  • orderBy(field: OrderBy, direction: OrderDirection = 'asc'): this - Add an "order by" clause to the query.
    • field - field name to work with
    • direction - direction of order (asc | desc)
  • limit(value: number): this - Set the "limit" value of the query.
    • value - limit records to count
  • offset(value: number): this - Set the "offset" value of the query.
    • value - offset for records
  • with(name: string, callback: EagerLoadConstraint = () => {}): this - Set the relationships that should be eager loaded.
    • name - relation name
    • callback - callback to load
  • withAll(callback: EagerLoadConstraint = () => {}): this - Set to eager load all top-level relationships. Constraint is set for all relationships.
    • callback - callback to load
  • withAllRecursive(depth: number = 3): this - Set to eager load all relationships recursively.
    • depth - relations depth to load
  • all(): Collection<M> - Get all models from the store. The difference with the `get` is that this method will not process any query chain. It'll always retrieve all models.
  • get(): Collection<M> - Retrieve models by processing whole query chain.
  • first(): Item<M> - Execute the query and get the first result.
  • find(id: string | number): Item<M> - Find a model by its primary key.
    • id - primary key value of needed item
  • find(ids: (string | number)[]): Collection<M> - Find multiple models by their primary keys.
    • ids - primary keys array of needed items
  • findIn(ids: (string | number)[]): Collection<M> - Find multiple models by their primary keys.
    • ids - primary keys array of needed items
  • select(): Collection<M> - Retrieve models by processing all filters set to the query chain.
  • load(models: Collection<M>): Collection<M> - Eager load relations on the model.
    • models - models array for relations load
  • revive(schema: Element[]): Collection<M> - Retrieves the models from the store by following the given normalized schema.
    • schema - elements to revive
  • revive(schema: Element): Item<M> - Retrieves the model from the store by following the given normalized schema.
    • schema - element to revive
  • reviveOne(schema: Element): Item<M> - Revive single model from the given schema.
    • schema - element to revive
  • reviveMany(schema: Element[]): Collection<M> - Revive multiple models from the given schema.
    • schema - elements to revive
  • new(): M - Create and persist model with default values.
  • save(records: Element[]): M[] - Save the given records to the store with data normalization.
    • records - elements to save
  • save(record: Element): M - Save the given records to the store with data normalization.
    • record - element to save
  • saveElements(elements: Elements): void - Save the given elements to the store.
    • elements - elements map to save
  • insert(records: Element[]): Collection<M> - Insert the given record to the store.
    • records - elements to insert
  • insert(record: Element): M - Insert the given record to the store.
    • record - element to insert
  • fresh(records: Element[]): Collection<M> - Insert the given records to the store by replacing any existing records.
    • records - new elements
  • fresh(record: Element): M - Insert the given record to the store by replacing any existing records.
    • record - new element
  • update(record: Element): Collection<M> - Update the record matching the query chain.
    • record - element update payload
  • destroy(ids: (string | number)[]): Collection<M> - Destroy the models for the given ids.
    • ids - primary keys to destroy
  • destroy(id: string | number): Item<M> - Destroy the models for the given id.
    • id - primary key to destroy
  • delete(): M[] - Delete records resolved by the query chain.
  • flush(): Collection<M> - Delete all records in the store.

RattusContext

Properties

  • $database: Database - instance of first (main) database
  • $databases: Record<string, Database> = {} - all databases storage

Methods

  • constructor(dataProvider: DataProvider) - Create context with DataProvider passed
    • dataProvider - chosen DataProvider
  • constructor(mainDatabase: Database) - Create context with Database passed. DataProvider will be inferred from database.
    • mainDatabase - main database in context
  • createDatabase(connection: string = 'entities', isPrimary = false): Database - Create database, save it in context and return.
    • connection - connection name for new database
    • isPrimary - should new database become "main" database
  • $repo<R extends Repository<InstanceType<M>>, M extends typeof Model = typeof Model>(model: M, connection?: string): R - Get repository for model from database from specific connection
    • model - model for which a repository is needed
    • connection - database connection name

Repository

Properties

  • static _isRepository: boolean = true - A special flag to indicate if this is the repository class or not. It's used when retrieving repository instance from `store.$repo()` method to determine whether the passed in class is either a repository or a model.
  • use: typeof Model - The model object to be used for the custom repository.

Methods

  • constructor(public database: Database) - Create a new Repository instance.
    • database - database to work with
  • initialize(model?: ModelConstructor<M>): this - Initialize the repository by setting the model instance.
    • model - model to initialize repository
  • getModel(): M - Get the model instance. If the model is not registered to the repository, it will throw an error. It happens when users use a custom repository without setting `use` property.
  • repo<M extends typeof Model>(model: M): Repository<InstanceType<M>> - Create a new repository with the given model.
    • model - model to create new repository for
  • query(): Query<M> - Create a new Query instance.
  • where(field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any): Query<M> - Add a basic where clause to the query.
    • field - field name to work with
    • value - optional value to match
  • orWhere(field: WherePrimaryClosure | string, value?: WhereSecondaryClosure | any): Query<M> - Add an "or where" clause to the query.
    • field - field name to work with
    • value - optional value to match
  • orderBy(field: OrderBy, direction?: OrderDirection): Query<M> - Add an "order by" clause to the query.
    • field - field name to work with
    • direction - direction of order (asc | desc)
  • limit(value: number): Query<M> - Set the "limit" value of the query.
    • value - limit records to count
  • offset(value: number): Query<M> - Set the "offset" value of the query.
    • value - offset for records
  • with(name: string, callback?: EagerLoadConstraint): Query<M> - Set the relationships that should be eager loaded.
    • name - relation name
    • callback - callback to load
  • withAll(callback?: EagerLoadConstraint): Query<M> - Set to eager load all top-level relationships. Constraint is set for all relationships.
    • callback - callback to load
  • withAllRecursive(depth?: number): Query<M> - Set to eager load all top-level relationships. Constraint is set for all relationships.
    • depth - relations depth to load
  • all(): Collection<M> - Get all models from the store.
  • find(id: string | number): Item<M> - Find a model by its primary key.
    • id - primary key value of needed item
  • find(ids: (string | number)[]): Collection<M> - Find multiple models by their primary keys.
    • ids - primary keys array of needed items
  • revive(schema: Element[]): Collection<M> - Retrieves the models from the store by following the given normalized schema.
    • schema - elements to revive
  • revive(schema: Element): Item<M> - Retrieves the model from the store by following the given normalized schema.
    • schema - element to revive
  • make(attributes?: Element): M - Create a new model instance. This method will not save the model to the store. It's pretty much the alternative to `new Model()`, but it injects the store instance to support model instance methods in SSR environment.
    • attributes - values for new model instance
  • save(records: Element[]): M[] - Save the given records to the store with data normalization.
    • records - elements to save
  • save(record: Element): M - Save the given records to the store with data normalization.
    • record - element to save
  • new(): M - Create and persist model with default values.
  • insert(records: Element[]): Collection<M> - Insert the given record to the store.
    • records - elements to insert
  • insert(record: Element): M - Insert the given record to the store.
    • record - element to insert
  • fresh(records: Element[]): Collection<M> - Insert the given records to the store by replacing any existing records.
    • records - new elements
  • fresh(record: Element): M - Insert the given record to the store by replacing any existing records.
    • record - new element
  • destroy(ids: (string | number)[]): Collection<M> - Destroy the models for the given ids.
    • ids - primary keys to destroy
  • destroy(id: string | number): Item<M> - Destroy the models for the given id.
    • id - primary key to destroy
  • flush(): M[] - Delete all records in the store.