### Update package.json Scripts for Migrations Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Example of how to integrate the migration script into the application's startup command in `package.json`. This ensures migrations are run every time the app starts. ```json scripts: { start: "sequelize db:migrate && node src/" } ``` -------------------------------- ### Install Sequelize CLI (Bash) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This bash command installs the Sequelize CLI globally on your system, which is necessary for managing database migrations. ```bash npm install sequelize-cli --save -g ``` -------------------------------- ### Install feathers-sequelize Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Install the feathers-sequelize adapter using npm. It's recommended to use the pre-release version for Feathers v5 compatibility. ```bash npm install --save feathers-sequelize@pre ``` -------------------------------- ### Install Feathers Sequelize Dependencies Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Installs the necessary FeathersJS core packages, Feathers Express, Feathers SocketIO, Sequelize, feathers-sequelize, and the SQLite3 driver for database interaction. ```bash $ npm install @feathersjs/feathers @feathersjs/errors @feathersjs/express @feathersjs/socketio sequelize feathers-sequelize sqlite3 ``` -------------------------------- ### Install Sequelize Database Drivers Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Install the appropriate database driver for your Sequelize dialect. This includes drivers for PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. ```bash npm install --save pg pg-hstore ``` ```bash npm install --save mysql2 // For both mysql and mariadb dialects ``` ```bash npm install --save sqlite3 ``` ```bash npm install --save tedious // MSSQL ``` -------------------------------- ### Query with Sequelize Operators Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Demonstrates how to use Sequelize operators within Feathers queries, even deprecated string-based ones, thanks to `feathers-sequelize`'s secure conversion. The example shows finding users whose names start with 'Dav' using the `$like` operator. ```javascript app.service('users').find({ query: { name: { $like: 'Dav%' } } }); ``` -------------------------------- ### Feathers Server with SQLite Sequelize Model Example Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Sets up a basic Feathers server using Express and SocketIO, integrating with a SQLite database via feathers-sequelize. It defines a 'message' model, configures a REST and SocketIO service for messages with pagination, and demonstrates creating an initial record. ```typescript import path from 'path'; import { feathers } from '@feathersjs/feathers'; import express from '@feathersjs/express'; import socketio from '@feathersjs/socketio'; import Sequelize from 'sequelize'; import SequelizeService from 'feathers-sequelize'; const sequelize = new Sequelize('sequelize', '', '', { dialect: 'sqlite', storage: path.join(__dirname, 'db.sqlite'), logging: false }); const Message = sequelize.define('message', { text: { type: Sequelize.STRING, allowNull: false } }, { freezeTableName: true }); // Create an Express compatible Feathers application instance. const app = express(feathers()); // Turn on JSON parser for REST services app.use(express.json()); // Turn on URL-encoded parser for REST services app.use(express.urlencoded({ extended: true })); // Enable REST services app.configure(express.rest()); // Enable Socket.io services app.configure(socketio()); // Create an in-memory Feathers service with a default page size of 2 items // and a maximum size of 4 app.use('/messages', new SequelizeService({ Model: Message, paginate: { default: 2, max: 4 } })); app.use(express.errorHandler()); Message.sync({ force: true }).then(() => { // Create a dummy Message app.service('messages').create({ text: 'Message created on server' }).then(message => console.log('Created message', message)); }); // Start the server const port = 3030; app.listen(port, () => { console.log(`Feathers server listening on port ${port}`); }); ``` -------------------------------- ### Handle Sequelize Errors in Feathers Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Provides an example of how to retrieve the original Sequelize error from a FeathersError object. This is useful for debugging or specific error handling scenarios. ```javascript import { ERROR } from 'feathers-sequelize'; try { await sequelizeService.doSomething(); } catch(error) { // error is a FeathersError // Safely retrieve the Sequelize error const sequelizeError = error[ERROR]; } ``` -------------------------------- ### Pass Sequelize Options via params.sequelize Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Allows passing additional Sequelize options within the `params` object during service method calls, primarily for retrieving associations. This is typically set within a `before` hook. The example shows how to include associated `User` models in a `find` operation. ```javascript app.service('messages').hooks({ before: { find(context) { const sequelize = context.app.get('sequelizeClient'); const { User } = sequelize.models; context.params.sequelize = { include: [ User ] } return context; } } }); ``` -------------------------------- ### Modify Sequelize Model with getModel Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Provides a way to modify the Sequelize model used by the service, for example, by applying scopes or schemas. This is achieved by extending the `SequelizeService` class and overriding the `getModel` method to conditionally apply Sequelize model methods based on `params.sequelize`. ```javascript const { SequelizeService } = require('feathers-sequelize'); class Service extends SequelizeService { getModel(params) { let Model = this.options.Model; if (params?.sequelize?.scope) { Model = Model.scope(params.sequelize.scope); } if (params?.sequelize?.schema) { Model = Model.schema(params.sequelize.schema); } return Model; } } ``` -------------------------------- ### Add Up/Down Scripts for Column Modification Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Example of a Sequelize migration script to modify a column, allowing null values in the 'up' script and disallowing them in the 'down' script. It uses `queryInterface.changeColumn` and requires specifying the column type even if it doesn't change. ```javascript 'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.changeColumn('tableName', 'columnName', { type: Sequelize.STRING, allowNull: true }); }, down: function (queryInterface, Sequelize) { return queryInterface.changeColumn('tableName', 'columnName', { type: Sequelize.STRING, allowNull: false }); } }; ``` -------------------------------- ### Configure Sequelize CLI (.sequelizerc) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This JavaScript configuration file (`.sequelizerc`) tells the Sequelize CLI where to find your migration scripts, seeders, models, and configuration files within your project structure. ```javascript const path = 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') }; ``` -------------------------------- ### Initialize SequelizeService Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Initializes a new Feathers Sequelize service instance with the provided options. The `Model` option is required, specifying the Sequelize model definition. Other options like `id`, `raw`, `events`, `paginate`, `multi`, `operatorMap`, `operators`, and `filters` can be configured to customize service behavior. ```javascript const Model = require('./models/mymodel'); const { SequelizeService } = require('feathers-sequelize'); app.use('/messages', new SequelizeService({ Model })); app.use('/messages', new SequelizeService({ Model, id, events, paginate })); ``` -------------------------------- ### Hydrate Hook for Sequelize Instances Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Demonstrates using the `hydrate` hook in the 'after' phase to return Sequelize model instances. It also shows how to include associated models when hydrating. ```javascript import { hydrate } from 'feathers-sequelize'; export default { after: { // ... find: [hydrate()] // ... }, // ... }; // Or, if you need to include associated models, you can do the following: const includeAssociated = () => (context) => hydrate({ include: [{ model: context.app.services.fooservice.Model }] }); export default { after: { // ... find: [includeAssociated()] // ... }, // ... }; ``` -------------------------------- ### Apply Migrations using Sequelize CLI Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Command to apply all pending database migrations using the Sequelize command-line interface. This ensures the database schema is up-to-date. ```bash sequelize db:migrate ``` -------------------------------- ### Create New Sequelize Migration (Bash) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This bash command utilizes the Sequelize CLI to generate a new migration file. The `--name` flag allows you to provide a descriptive name for the migration, which will be included in the filename along with a timestamp to ensure proper execution order. ```bash sequelize migration:create --name="meaningful-name" ``` -------------------------------- ### Return Sequelize Instances with Raw: False Hook Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Shows how to configure Feathers to return Sequelize model instances instead of plain objects by setting `{ raw: false }` in a before hook. This allows direct use of Sequelize Instance methods. ```javascript const rawFalse = () => (context) => { if (!context.params.sequelize) context.params.sequelize = {}; Object.assign(context.params.sequelize, { raw: false }); return context; } export default { after: { // ... find: [rawFalse()] // ... }, // ... }; ``` -------------------------------- ### Configure Sequelize Migrations (migrations/config.js) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This JavaScript file configures the database connection details for Sequelize migrations. It specifies the dialect, connection URL, and the table name for storing migration history, dynamically loading settings based on the environment. ```javascript const app = require('../src/app'); const env = process.env.NODE_ENV || 'development'; const dialect = 'postgres'; // Or your dialect name module.exports = { [env]: { dialect, url: app.get(dialect), migrationStorageTableName: '_migrations' } }; ``` -------------------------------- ### Set Database Environment Variable (Bash) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This bash command demonstrates how to set the `DATABASE_URL` environment variable, which is often required by applications to establish a connection to the database. This is crucial for Sequelize commands to function correctly. ```bash DATABASE_URL=postgres://user:pass@host:port/dbname npm start ``` -------------------------------- ### Export Database Environment Variable (Bash) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This bash command shows how to export the `DATABASE_URL` environment variable for the current terminal session, simplifying the process of running subsequent database-related commands. ```bash export DATABASE_URL=postgres://user:pass@host:port/db ``` -------------------------------- ### Test Sequelize Query in Isolation (JavaScript) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This snippet demonstrates how to create a standalone JavaScript file to test Sequelize queries outside of the FeathersJS application. It involves setting up the Feathers app, accessing the Sequelize client, defining a model, and executing a `findAll` query with custom parameters. The results are logged to the console. ```javascript import app from from './src/app'; // run setup to initialize relations app.setup(); const seqClient = app.get('sequelizeClient'); const SomeModel = seqClient.models['some-model']; const log = console.log.bind(console); SomeModel.findAll({ /* * Build your custom query here. We will use this object later. */ }).then(log).catch(log); ``` -------------------------------- ### Define Sequelize Models (migrations/models.js) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This JavaScript file defines how Sequelize should load your application's models. It exports an object containing all Sequelize models, along with the Sequelize instance and constructor, which is required by the Sequelize CLI for migration tasks. ```javascript const Sequelize = require('sequelize'); const app = require('../src/app'); const sequelize = app.get('sequelizeClient'); const models = sequelize.models; // The export object must be a dictionary of model names -> models // It must also include sequelize (instance) and Sequelize (constructor) properties module.exports = Object.assign({ Sequelize, sequelize }, models); ``` -------------------------------- ### Integrate Custom Query with Feathers 'before' Hook (JavaScript) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md This JavaScript code illustrates how to integrate a tested custom Sequelize query into a FeathersJS service using a 'before' hook. The `buildCustomQuery` function modifies the `context.params.sequelize` object, allowing fine-grained control over the query passed to Sequelize by overriding default parameters like 'where', 'limit', 'offset', and 'order'. ```javascript function buildCustomQuery(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] } }); ``` -------------------------------- ### Dehydrate and Hydrate for Hook Compatibility Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Illustrates a common pattern where `hydrate` is used to work with Sequelize instances, and `dehydrate` is used to convert them back to plain objects for compatibility with other hooks like `feathers-hooks-common`'s `populate`. ```javascript import { dehydrate, hydrate } from 'feathers-sequelize'; import { populate } from 'feathers-hooks-common'; export default { after: { // ... find: [hydrate(), doSomethingCustom(), dehydrate(), populate()] // ... }, // ... }; ``` -------------------------------- ### Import SequelizeService Directly (Feathers v5) Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md In Feathers v5, the default export for feathers-sequelize has been removed. You must now import the SequelizeService class directly. This change aligns with Feathers v5 conventions. ```javascript import { SequelizeService } from 'feathers-sequelize'; app.use('/messages', new SequelizeService({ ... })); ``` -------------------------------- ### Undo the Previous Migration using Sequelize CLI Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Command to undo the most recently applied database migration using the Sequelize command-line interface. This is typically used during development to test migration scripts. ```bash sequelize db:migrate:undo ``` -------------------------------- ### Set Sequelize Include in Feathers Before Hook Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Demonstrates how to set the `params.sequelize.include` option in a Feathers before hook to eager load associated models. It shows how to conditionally include models based on query parameters and update the query to exclude the include parameter. ```javascript function (context) { const { include, ...query } = context.params.query; if (include) { const AssociatedModel = context.app.services.fooservice.Model; context.params.sequelize = { include: [{ model: AssociatedModel }] }; // Update the query to not include `include` context.params.query = query; } return context; } ``` -------------------------------- ### Configure operatorMap in Feathers Sequelize Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Feathers v5 introduces 'options.operators' and 'options.filters'. The previous 'options.operators' object is now renamed to 'options.operatorMap'. This allows mapping custom operators, like '$between', to Sequelize operators (e.g., Op.between). ```javascript import { SequelizeService } from 'feathers-sequelize'; import { Op } from 'sequelize'; app.use('/messages', new SequelizeService({ Model, // operators is now operatorMap: operatorMap: { $between: Op.between } })); ``` -------------------------------- ### Querying Nested Columns with Feathers Sequelize Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Illustrates how to query based on a column in an associated model using Sequelize's nested column syntax within a Feathers query. It highlights the need to whitelist such queries in the service options. ```javascript // Find a user with post.id == 120 app.service('users').find({ query: { '$post.id$': 120, include: { model: posts } } }); ``` -------------------------------- ### Configure MSSQL Default Sort Order Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Ensures a default sort order for MSSQL databases to prevent 'Invalid usage of the option NEXT in the FETCH statement.' errors. This can be applied globally via model hooks or per-request using Feathers hooks. ```javascript model.beforeFind(model => model.order.push(['id', 'ASC'])) ``` ```javascript export default function (options = {}) { return async context => { const { query = {} } = context.params; // Sort by id field ascending (or any other property you want) // See https://docs.feathersjs.com/api/databases/querying.html#sort const $sort = { id: 1 }; context.params.query = { $sort: { }, ...query } return context; } } ``` -------------------------------- ### Add Column with Conditional Logic Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Demonstrates a Sequelize migration that adds a new column to a table only if it doesn't already exist. The 'down' script removes the column if it exists. This ensures application code stays in sync with migrations. ```javascript 'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.describeTable('tableName').then(attributes => { if ( !attributes.columnName ) { return queryInterface.addColumn('tableName', 'columnName', { type: Sequelize.INTEGER, defaultValue: 0 }); } }) }, down: function (queryInterface, Sequelize) { return queryInterface.describeTable('tableName').then(attributes => { if ( attributes.columnName ) { return queryInterface.removeColumn('tableName', 'columnName'); } }); } }; ``` -------------------------------- ### Implement Filters Option in Feathers Sequelize Source: https://github.com/feathersjs-ecosystem/feathers-sequelize/blob/master/README.md Feathers v5 introduces a new 'filters' option to verify filters. This object is used to declare and validate custom filters, including those using dollar notation like '$and' or '$person.name$'. ```javascript import { SequelizeService } from 'feathers-sequelize'; app.use('/messages', new SequelizeService({ Model, filters: { '$and': true, '$person.name$': true } })); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.