1.0.4 • Published 5 years ago

fastify-waterline v1.0.4

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

fastify-waterline

js-standard-style Build Status Greenkeeper badge npm-version

fastify-waterline add a Waterline ORM instance to your Fastify project.

What is Waterline?

Waterline is a datastore-agnostic tool that dramatically simplifies interaction with one or more databases. It provides an abstraction layer on top of the underlying database, allowing you to easily query and manipulate your data without writing vendor-specific integration code.

Install

npm i fastify-waterline --save

Usage

First of all you need to define a model. A model represents a set of structured data, called records. Models usually correspond to a table/collection in a database, attributes correspond to columns/fields, and records correspond to rows/documents. Here is an example:

// file models/user.js
'use strict'

module.exports = {
  attributes: {
    id: {
      type: 'number',
      autoMigrations: { autoIncrement: true }
    },
    firstName: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },
    username: {
      type: 'string',
      required: true
    }
  },
  primaryKey: 'id',
  tableName: 'users'
}

Now let's imagine that this model represent a table in a MySQL database called test. Now we can add the fastify-waterline plugin at our fastify instance in this way:

const fastify = Fastify()
fastify.register(require('fastify-waterline'), [{
  name: 'mysql',
  adapter: 'mysql',
  host: 'localhost',
  port: 3306,
  user: 'root',
  database: 'test',
  entitiesFolder: './models'
}])

fastify.ready(async err => {
  if (err) {
    fastify.log.error(err)
  }

  const UserModel = await fastify.fw.getModel('user')
  let newUser = await UserModel.create({
    firstName: 'Davide',
    lastName: 'D\'Antonio',
    username: 'ddantonio'
  }).meta({ fetch: true })
})

The Fastify instance expose two methods getModel and getInstance

Options

OptionDescription
nameThe name of the connection
adapterThe adapter that must be used. One of mysql, mongo, postgresql, disk
hostThe database host
portThe database port
userThe database user
passwordThe database password
entitiesFolderThe folder path of our .js entities files
entitiesAn array of entities for example [ require('./models/user'), require('./models/post') ]

Other available options can be found on here

Contributing

If you feel you can help in any way, be it with examples, extra testing, or new features please open a pull request or open an issue.

The code follows the Standard code style.

js-standard-style

Acknowledgements

This project is kindly sponsored by Webeetle

License

Licensed under MIT.