1.0.1 • Published 3 years ago

fastify-data v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
3 years ago

GitHub release (latest by date) npm GitHub

GitHub Workflow Status (branch) GitHub branch checks state Coveralls github branch GitHub issues GitHub closed issues

GitHub code size in bytes npm GitHub all releases

  • uses typeorm
  • supports multiple data sources
  • easy to use and operate

Installation

  • install with npm:

    npm i fastify-data
  • install with yarn:

    yard add fastify-data

Usage

1. Step: Setup

const app = require('fastify')();
const fastifyData = require('fastify-data');

const employeeSchema = {
  tableName: 'People',
  name: 'Person',
  columns: {
    id: { type: 'integer', primary: true, generated: true },
    firstName: { type: 'text', nullable: false },
    lastName: { type: 'text', nullable: false }
  }
};

const sqliteOptions = {
  name: 'db1',
  type: 'better-sqlite3',
  database: 'demo.db',
  synchronize: true,
  entities: [employeeSchema]
};

const mysqlOptions = {
  name: 'db2',
  type: 'mysql',
  username: 'root',
  password: 'demo',
  database: 'demo',
  synchronize: true,
  entities: [employeeSchema]
};

app.register(fastifyData, { dataSources: [sqliteOptions, mysqlOptions] });

2. Step: Using in handler

app.post('/register', function (req, res) {
  req
    .getDataSource('db1')
    .then(ds => ds.getRepository('Employee'))
    .then(repository => repository.save({ firstName: 'Jane', lastName: 'Doe' }))
    .then(entity => res.code(201).send(entity))
    .catch(err => res.code(500).send(err.message));
});

app.get('/profile', (req, res) => {
  req
    .getDataSource('db2')
    .then(ds => ds.getRepository('Employee'))
    .then(repository => repository.findOne({ where: { id: req.query.id } }))
    .then(entity => {
      if (entity) {
        res.code(200).send({ status: 'success', data: entity });
      } else {
        res.code(404).send({ status: 'fail', message: 'employee not found' });
      }
    })
    .catch(err => res.code(500).send(err.message));
});

app.put('/update', async (req, res) => {
  const { firstName, lastName, id } = req.body;

  // get data source
  const ds = await req.getDataSource('db2');
  // get repository and update the employee
  const entity = await ds.getRepository('Employee').save({ firstName, lastName, id });

  return { status: 'access', data: entity };
});

License

Licensed under MIT.