Skip to content

E. Datasources

Jonathan Casarrubias edited this page Jun 11, 2018 · 2 revisions

alt text

Description

In this section, you will learn how to create and configure an OnixJS Datasource.

One of the great advantages of using the OnixJS Platform is that you are able to decide using one or multiple data sources.

When creating a data-source you are able to define which database and orm to use, later you will be able to decide which OnixJS Models uses any of those sources.

Example

As the previous examples, a data source class will also be decorated but in this case, you will be required to implement the IDataSoruce interface, because in this case you are required to add some logic in order to setup your selected ORM and then to register any model using this data source.

import { Mongoose, Schema } from 'mongoose';
import { IDataSource, DataSource, IModelRegister } from '@onixjs/core';

@DataSource()
export class MongooseDatasource implements IDataSource {

  private mongoose: Mongoose = new Mongoose();

  async connect(): Promise<Mongoose> {
    return this.mongoose.connect('mongodb://user:pass@host:27017/database');
  }

  async disconnect(): Promise<void> {
    return this.mongoose.disconnect();
  }

  async register(register: IModelRegister) {
    register.model = this.mongoose.model(register.class.name, register.schema);
    return register;
  }
}

The logic in this Class is quite simple... Actually, you are required to create an instance of your selected ORM and then simply obey their documentation in order to connect and disconnect from a database.

The OnixJS Framework will execute those connect methods once at boot time, the disconnect on unloading the framework and the register will be executed once a model is injected by the first time within a module scope.

Injectable models are singletons that only instantiates once, further injections will use the already created model instance.

How to register a model

As the example states, you will be required to follow your ORM documentation in order to create an instance, since different ORMs uses different approaches, based in our research we will be providing you with 3 parameters.

  • Class: The actual model class, it can be used to get the model class name.
  • model: The instance for that model class, ORMs like TypeORM will require you to actually use that instance.
  • schema: A JSON Schema representing your model, some ORMs like Mongoose actually require a JSON schema and not an instance.

HINT: You are free to use as many data sources and ORMs in the same project as you require.

Clone this wiki locally