Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Feathers service adapter for the Sequelize ORM. Supporting MySQL, MariaDB, Postgres, SQLite, and SQL Server

License

NotificationsYou must be signed in to change notification settings

feathersjs-ecosystem/feathers-sequelize

Repository files navigation

CIDownload StatusDiscord

Caution: When you're using feathers v4 and want to upgrade to feathers v5, please make sure to read themigration guide.

NOTE: This is the version for Feathers v5. For Feathers v4 usefeathers-sequelize v6

AFeathers database adapter forSequelize, an ORM for Node.js. It supports PostgreSQL, MySQL, MariaDB, SQLite and MSSQL and features transaction support, relations, read replication and more.

Very Important: Before using this adapter you have to be familiar with both, theFeathers Basics and general use ofSequelize. For associations and relations see theassociations section. This adapter may not cover all use cases but they can still be implemented using Sequelize models directly in aCustom Feathers service.

npm install --save feathers-sequelize@pre

Andone of the following:

npm install --save pg pg-hstorenpm install --save mysql2 // For both mysql and mariadb dialectsnpm install --save sqlite3npm install --save tedious // MSSQL

Important:feathers-sequelize implements theFeathers Common database adapter API andquerying syntax.For more information about models and general Sequelize usage, follow up in theSequelize documentation.

API

new SequelizeService(options)

Returns a new service instance initialized with the given options.

constModel=require('./models/mymodel');const{ SequelizeService}=require('feathers-sequelize');app.use('/messages',newSequelizeService({ Model}));app.use('/messages',newSequelizeService({ Model, id, events, paginate}));

Options:

  • Model (required) - The Sequelize model definition
  • id (optional, default: primary key of the model) - The name of the id field property. Will use the first property withprimaryKey: true by default.
  • raw (optional, default:true) - Runs queries faster by returning plain objects instead of Sequelize models.
  • Sequelize (optional, default:Model.sequelize.Sequelize) - The Sequelize instance
  • events (optional) - A list ofcustom service events sent by this service
  • paginate (optional) - Apagination object containing adefault andmax page size
  • multi (optional) - Allowcreate with arrays andupdate andremove withidnull to change multiple items. Can betrue for all methods or an array of allowed methods (e.g.[ 'remove', 'create' ])
  • operatorMap (optional) - A mapping from query syntax property names to toSequelize secure operators
  • operators (optional) - An array of additional query operators to allow (e..g[ '$regex', '$geoNear' ]). Default is the supportedoperators
  • filters (optional) - An object of additional query parameters to allow (e..g{ '$post.id$': true }).`

params.sequelize

When making aservice method call,params can contain ansequelize property which allows to pass additional Sequelize options. This can e.g. be used toretrieve associations. Normally this wil be set in a beforehook:

app.service('messages').hooks({before:{find(context){// Get the Sequelize instance. In the generated application via:constsequelize=context.app.get('sequelizeClient');const{ User}=sequelize.models;context.params.sequelize={include:[User]}returncontext;}}});

Other options thatparams.sequelize allows you to pass can be found inSequelize querying docs.Beware that when setting atop-levelwhere property (usually for querying based on a column on an associated model), thewhere inparams.sequelize will overwrite yourquery.

This library offers some additional functionality when usingsequelize.returning in services that supportmulti. Themulti option allows you to create, patch, and remove multiple records at once. When usingsequelize.returning withmulti, thesequelize.returning is used to indicate if the method should return any results. This is helpful when updating large numbers of records and you do not need the API (or events) to be bogged down with results.

operatorMap

Sequelize deprecated string based operators a while ago for security reasons. Starting at version 4.0.0feathers-sequelize converts queries securely, so you can still use string based operators listed below. If you want to support additional Sequelize operators, theoperatorMap service option can contain a mapping from query parameter name to Sequelize operator. By default supported are:

'$eq','$ne','$gte','$gt','$lte','$lt','$in','$nin','$like','$notLike','$iLike','$notILike','$or','$and'
// Find all users with name similar to Davapp.service('users').find({query:{name:{$like:'Dav%'}}});
GET /users?name[$like]=Dav%

Modifying the Model

Sequelize allows you to call methods likeModel.scope(),Model.schema(), and others. To use these methods, extend the class to overwrite thegetModel method.

const{ SequelizeService}=require('feathers-sequelize');classServiceextendsSequelizeService{getModel(params){letModel=this.options.Model;if(params?.sequelize?.scope){Model=Model.scope(params.sequelize.scope);}if(params?.sequelize?.schema){Model=Model.schema(params.sequelize.schema);}returnModel;}}

Caveats

Sequelizeraw queries

By default, allfeathers-sequelize operations will returnraw data (usingraw: true when querying the database). This results in faster execution and allows feathers-sequelize to interoperate with feathers-common hooks and other 3rd party integrations. However, this will bypass some of the "goodness" you get when using Sequelize as an ORM:

  • custom getters/setters will be bypassed
  • model-level validations are bypassed
  • associated data loads a bit differently
  • ...and several other issues that one might not expect

Don't worry! The solution is easy. Please read the guides aboutworking with model instances. You can also pass{ raw: true/false} inparams.sequelize to change the behavior per service call.

Working with MSSQL

When using MSSQL as the database, a default sort order always has to be applied, otherwise the adapter will throw anInvalid usage of the option NEXT in the FETCH statement. error. This can be done in your model with:

model.beforeFind(model=>model.order.push(['id','ASC']))

Or in a hook like this:

exportdefaultfunction(options={}){returnasynccontext=>{const{ query={}}=context.params;// Sort by id field ascending (or any other property you want)// See https://docs.feathersjs.com/api/databases/querying.html#sortconst$sort={id:1};context.params.query={$sort:{},      ...query}returncontext;}}

Primary keys

All tables used by a feathers-sequelize service require a primary key. Although it is common practice for many-to-many tables to not have a primary key, this service will break if the table does not have a primary key. This is because most service methods require an ID and because of how feathers maps services to URLs.

Example

Here is an example of a Feathers server with amessages SQLite Sequelize Model:

$ npm install @feathersjs/feathers @feathersjs/errors @feathersjs/express @feathersjs/socketio sequelize feathers-sequelize sqlite3

Inapp.js:

importpathfrom'path';import{feathers}from'@feathersjs/feathers';importexpressfrom'@feathersjs/express';importsocketiofrom'@feathersjs/socketio';importSequelizefrom'sequelize';importSequelizeServicefrom'feathers-sequelize';constsequelize=newSequelize('sequelize','','',{dialect:'sqlite',storage:path.join(__dirname,'db.sqlite'),logging:false});constMessage=sequelize.define('message',{text:{type:Sequelize.STRING,allowNull:false}},{freezeTableName:true});// Create an Express compatible Feathers application instance.constapp=express(feathers());// Turn on JSON parser for REST servicesapp.use(express.json());// Turn on URL-encoded parser for REST servicesapp.use(express.urlencoded({extended:true}));// Enable REST servicesapp.configure(express.rest());// Enable Socket.io servicesapp.configure(socketio());// Create an in-memory Feathers service with a default page size of 2 items// and a maximum size of 4app.use('/messages',newSequelizeService({Model:Message,paginate:{default:2,max:4}}));app.use(express.errorHandler());Message.sync({force:true}).then(()=>{// Create a dummy Messageapp.service('messages').create({text:'Message created on server'}).then(message=>console.log('Created message',message));});// Start the serverconstport=3030;app.listen(port,()=>{console.log(`Feathers server listening on port${port}`);});

Run the example withnode app and go tolocalhost:3030/messages.

Associations

Embrace the ORM

The documentation onSequelize associations and relations is essential to implementing associations with this adapter and one of the steepest parts of the Sequelize learning curve. If you have never used an ORM, let it do a lot of the heavy lifting for you!

Settingparams.sequelize.include

Once you understand how theinclude option works with Sequelize, you will want to set that option from abefore hook in Feathers. Feathers will pass the value ofcontext.params.sequelize as the options parameter for all Sequelize method calls. This is what your hook might look like:

// GET /my-service?name=John&include=1function(context){const{ include, ...query}=context.params.query;if(include){constAssociatedModel=context.app.services.fooservice.Model;context.params.sequelize={include:[{model:AssociatedModel}]};// Update the query to not include `include`context.params.query=query;}returncontext;}

Underneath the hood, feathers will call your models find method sort of like this:

// YourModel is a sequelize modelconstoptions=Object.assign({where:{name:'John'}},context.params.sequelize);YourModel.findAndCount(options);

For more information, follow up up in theSequelize documentation for associations andthis issue.

Querying

Additionally to thecommon querying mechanism this adapter also supports allSequelize query operators.

Querying a nested column

To query based on a column in an associated model, you can use Sequelize'snested column syntax in a query. The nested column syntax is considered afilter by Feathers, and so each such usage has to bewhitelisted.

Example:

// Find a user with post.id == 120app.service('users').find({query:{'$post.id$':120,include:{model:posts}}});

For this case to work, you'll need to add '$post.id$' to the service options''filters' property.

Working with Sequelize Model instances

It is highly recommended to useraw queries, which is the default. However, there are times when you will want to take advantage ofSequelize Instance methods. There are two ways to tell feathers to return Sequelize instances:

  1. Set{ raw: false } in a "before" hook:

    constrawFalse=()=>(context)=>{if(!context.params.sequelize)context.params.sequelize={};Object.assign(context.params.sequelize,{raw:false});returncontext;}exportdefault{after:{// ...find:[rawFalse()]// ...},// ...};
  2. Use thehydrate hook in the "after" phase:

    import{hydrate}from'feathers-sequelize';exportdefault{after:{// ...find:[hydrate()]// ...},// ...};// Or, if you need to include associated models, you can do the following:constincludeAssociated=()=>(context)=>hydrate({include:[{model:context.app.services.fooservice.Model}]});exportdefault{after:{// ...find:[includeAssociated()]// ...},// ...};

For a more complete example see thisgist.

Important: When working with Sequelize Instances, most of the feathers-hooks-common will no longer work. If you need to use a common hook or other 3rd party hooks, you should use the "dehydrate" hook to convert data back to a plain object:

import{dehydrate,hydrate}from'feathers-sequelize';import{populate}=from'feathers-hooks-common';exportdefault{after:{// ...find:[hydrate(),doSomethingCustom(),dehydrate(),populate()]// ...},// ...};

Validation

Sequelize by default gives you the ability toadd validations at the model level. Using an error handler like the one thatcomes with Feathers your validation errors will be formatted nicely right out of the box!

Errors

Errors do not contain Sequelize specific information. The original Sequelize error can be retrieved on the server via:

import{ERROR}=from'feathers-sequelize';try{awaitsequelizeService.doSomething();}catch(error){// error is a FeathersError// Safely retrieve the Sequelize errorconstsequelizeError=error[ERROR];}

Testing sequelize queries in isolation

If you wish to use some of the more advanced features of sequelize, you should first test your queries in isolation (without feathers). Once your query is working, you can integrate it into your feathers app.

1. Build a test file

Create a temporary file in your project root like this:

// test.jsimportappfromfrom'./src/app';// run setup to initialize relationsapp.setup();constseqClient=app.get('sequelizeClient');constSomeModel=seqClient.models['some-model'];constlog=console.log.bind(console);SomeModel.findAll({/*  * Build your custom query here. We will use this object later.  */}).then(log).catch(log);

And then run this file like this:

node test.js

Continue updating the file and running it until you are satisfied with the results.

2. Integrate the query using a "before" hook

Once your have your custom query working to your satisfaction, you will want to integrate it into your feathers app. Take the guts of thefindAll operation above and create a "before" hook:

functionbuildCustomQuery(context){context.params.sequelize={/*        * This is the same object you passed to "findAll" above.        * This object is *shallow merged* onto the underlying query object        * generated by feathers-sequelize (it is *not* a deep merge!).        * The underlying data will already contain the following:        *   - "where" condition based on query paramters        *   - "limit" and "offset" based on pagination settings        *   - "order" based $sort query parameter        * You can override any/all of the underlying data by setting it here.        * This gives you full control over the query object passed to sequelize!        */};}someService.hooks({before:{find:[buildCustomQuery]}});

Migrations

Migrations with feathers and sequelize are quite simple. This guide will walk you through creating the recommended file structure, but you are free to rearrange things as you see fit. The following assumes you have amigrations folder in the root of your app.

Initial Setup: one-time tasks

npm install sequelize-cli --save -g
  • Create a.sequelizerc file in your project root with the following content:
constpath=require('path');module.exports={'config':path.resolve('migrations/config.js'),'migrations-path':path.resolve('migrations/scripts'),'seeders-path':path.resolve('migrations/seeders'),'models-path':path.resolve('migrations/models.js')};
  • Create the migrations config inmigrations/config.js:
constapp=require('../src/app');constenv=process.env.NODE_ENV||'development';constdialect='postgres';// Or your dialect namemodule.exports={[env]:{    dialect,url:app.get(dialect),migrationStorageTableName:'_migrations'}};
  • Define your models config inmigrations/models.js:
constSequelize=require('sequelize');constapp=require('../src/app');constsequelize=app.get('sequelizeClient');constmodels=sequelize.models;// The export object must be a dictionary of model names -> models// It must also include sequelize (instance) and Sequelize (constructor) propertiesmodule.exports=Object.assign({  Sequelize,  sequelize},models);

Migrations workflow

The migration commands will load your application and it is therefore required that you define the same environment variables as when running your application. For example, many applications will define the database connection string in the startup command:

DATABASE_URL=postgres://user:pass@host:port/dbname npm start

All of the following commands assume that you have defined the same environment variables used by your application.

ProTip: To save typing, you can export environment variables for your current bash/terminal session:

export DATABASE_URL=postgres://user:pass@host:port/db

Create a new migration

To create a new migration file, run the following command and provide a meaningful name:

sequelize migration:create --name="meaningful-name"

This will create a new file in themigrations/scripts folder. All migration file names will be prefixed with a sortable data/time string:20160421135254-meaningful-name.js. This prefix is crucial for making sure your migrations are executed in the proper order.

NOTE: The order of your migrations is determined by the alphabetical order of the migration scripts in the file system. The file names generated by the CLI tools will always ensure that the most recent migration comes last.

Add the up/down scripts:

Open the newly created migration file and write the code to both apply and undo the migration. Please refer to thesequelize migration functions for available operations.Do not be lazy - write the down script too and test! Here is an example of converting aNOT NULL column accept null values:

'use strict';module.exports={up:function(queryInterface,Sequelize){returnqueryInterface.changeColumn('tableName','columnName',{type:Sequelize.STRING,allowNull:true});},down:function(queryInterface,Sequelize){returnqueryInterface.changeColumn('tableName','columnName',{type:Sequelize.STRING,allowNull:false});}};

ProTip: As of this writing, if you use thechangeColumn method you mustalways specify thetype, even if the type is not changing.

ProTip: Down scripts are typically easy to create and should be nearly identical to the up script except with inverted logic and inverse method calls.

Keeping your app code in sync with migrations

The application code should always be up to date with the migrations. This allows the app to be freshly installed with everything up-to-date without running the migration scripts. Your migrations should also never break a freshly installed app. This often times requires that you perform any necessary checks before executing a task. For example, if you update a model to include a new field, your migration should first check to make sure that new field does not exist:

'use strict';module.exports={up:function(queryInterface,Sequelize){returnqueryInterface.describeTable('tableName').then(attributes=>{if(!attributes.columnName){returnqueryInterface.addColumn('tableName','columnName',{type:Sequelize.INTEGER,defaultValue:0});}})},down:function(queryInterface,Sequelize){returnqueryInterface.describeTable('tableName').then(attributes=>{if(attributes.columnName){returnqueryInterface.removeColumn('tableName','columnName');}});}};

Apply a migration

The CLI tools will always run your migrations in the correct order and will keep track of which migrations have been applied and which have not. This data is stored in the database under the_migrations table. To ensure you are up to date, simply run the following:

sequelize db:migrate

ProTip: You can add the migrations script to your application startup command to ensure that all migrations have run every time your app is started. Try updating your package.jsonscripts attribute and runnpm start:

scripts: {    start: "sequelize db:migrate && node src/"}

Undo the previous migration

To undo the last migration, run the following command:

sequelize db:migrate:undo

Continue running the command to undo each migration one at a time - the migrations will be undone in the proper order.

Note: - You shouldn't really have to undo a migration unless you are the one developing a new migration and you want to test that it works. Applications rarely have to revert to a previous state, but when they do you will be glad you took the time to write and test yourdown scripts!

Reverting your app to a previous state

In the unfortunate case where you must revert your app to a previous state, it is important to take your time and plan your method of attack. Every application is different and there is no one-size-fits-all strategy for rewinding an application. However, most applications should be able to follow these steps (order is important):

  1. Stop your application (kill the process)
  2. Find the last stable version of your app
  3. Count the number of migrations which have been added since that version
  4. Undo your migrations one at a time until the db is in the correct state
  5. Revert your code back to the previous state
  6. Start your app

License

Copyright (c) 2024

Licensed under theMIT license.

whitelist

Thewhitelist property is no longer, you should usefilters instead. Checkout the migration guide below.

Feathers v5 introduces a convention foroptions.operators andoptions.filters. The way feathers-sequelize worked in previous version is not compatible with these conventions. Please readhttps://dove.feathersjs.com/guides/migrating.html#custom-filters-operators.

Migrate to Feathers v5 (dove)

There are several breaking changes for feathers-sequelize in Feathers v5. This guide will help you to migrate your existing Feathers v4 application to Feathers v5.

Named export

The default export offeathers-sequelize has been removed. You now have to import theSequelizeService class directly:

import{SequelizeService}from'feathers-sequelize';app.use('/messages',newSequelizeService({ ...}));

This follows conventions from feathers v5.

operators / operatorMap

Feathers v5 introduces a convention foroptions.operators andoptions.filters. The way feathers-sequelize worked in previous version is not compatible with these conventions. Please readhttps://dove.feathersjs.com/guides/migrating.html#custom-filters-operators first.

The oldoptions.operators object is renamed tooptions.operatorMap:

import{SequelizeService}from'feathers-sequelize';import{Op}from'sequelize';app.use('/messages',newSequelizeService({  Model,// operators is now operatorMap:operatorMap:{$between:Op.between}}));

filters

Feathers v5 introduces a convention foroptions.operators andoptions.filters. The way feathers-sequelize worked in previous version is not compatible with these conventions. Please readhttps://dove.feathersjs.com/guides/migrating.html#custom-filters-operators first.

Feathers v5 introduces a newfilters option. It is an object to verify filters. Here you need to add$dollar.notation$ operators, if you have some.

import{SequelizeService}from'feathers-sequelize';app.use('/messages',newSequelizeService({  Model,filters:{'$and':true,'$person.name$':true}}));

About

A Feathers service adapter for the Sequelize ORM. Supporting MySQL, MariaDB, Postgres, SQLite, and SQL Server

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors45


[8]ページ先頭

©2009-2025 Movatter.jp