Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Common API

The Feathers database adapters implement a common interface for initialization, pagination, extending and querying. This chapter describes the common adapter initialization and options, how to enable and use pagination, the details on how specific service methods behave and how to extend an adapter with custom functionality.

Important

Every database adapter is an implementation of theFeathers service interface. If there is no adapter available for your database of choice, you can still use it directly in acustom service. We recommend being familiar with Feathers services, service events and hooks and the database before using a database adapter.

Initialization

new <Name>Service(options)

Each adapter exports a<Name>Service class that can be exported and extended.

ts
import { NameService } from 'feathers-<name>'app.use('/messages', new NameService())app.use('/messages', new NameService({id,events,paginate }))

Options

The following options are available for all database adapters:

  • id {string} (optional) - The name of the id field property (usually set by default toid or_id).
  • paginate {Object} (optional) - Apagination object containing adefault andmax page size
  • multi {string[]|boolean} (optional, default:false) - Allowcreate with arrays andpatch andremove with idnull to change multiple items. Can betrue for all methods or an array of allowed methods (e.g.[ 'remove', 'create' ])

The following legacy options are still available but should be avoided:

  • events {string[]} (optional,deprecated) - A list ofcustom service events sent by this service. Use theevents option whenregistering the service with app.use instead.
  • operators {string[]} (optional,deprecated) - A list of additional non-standard query parameters to allow (e.g[ '$regex' ]). Not necessary when using aquery schema
  • filters {Object} (optional,deprecated) - An object of additional top level query filters, e.g.{ $populate: true }. Can also be a converter function like{ $ignoreCase: (value) => value === 'true' ? true : false }. Not necessary when using aquery schema

For database specific options see the adapter documentation.

Pagination

When initializing an adapter you can set the following pagination options in thepaginate object:

  • default - Sets the default number of items when$limit is not set
  • max - Sets the maximum allowed number of items per page (even if the$limit query parameter is set higher)

Whenpaginate.default is set,find will return apage object (instead of the normal array) in the following form:

{  "total": "<total number of records>",  "limit": "<max number of items per page>",  "skip": "<number of skipped items (offset)>",  "data": [/* data */]}

The pagination options can be set as follows:

js
const service = require('feathers-<db-name>')// Set the `paginate` option during initializationapp.use(  '/todos',  service({    paginate: {      default: 5,      max: 25    }  }))// override pagination in `params.paginate` for this callapp.service('todos').find({  paginate: {    default: 100,    max: 200  }})// disable pagination for this callapp.service('todos').find({  paginate: false})

note

Disabling or changing the default pagination is not available in the client. Onlyparams.query is passed to the server (also see aworkaround here)

params.adapter

Setting theadapter in theservice methodparams allows do dynamically modify the database adapter options based on the request. This e.g. allows to temporarily allow multiple entry creation/changes or the pagination settings.

ts
constmessages = [  {    text:'message 1'  },  {    text:'message 2'  }]// Enable multiple entry insertion for this requestapp.service('messages').create(messages, {  adapter: {    multi:true  }})

tip

If the adapter has aModel option,params.adapter.Model can be used to point to different databases based on the request to e.g. allow multi-tenant systems. This is usually done by settingcontext.params.adapter in ahook.

params.paginate

Settingpaginate in theservice methodparams allows to change or disable the default pagination for a single request:

ts
// Get all messages as an arrayconstallMessages = await app.service('messages').find({  paginate:false})

Extending Adapters

There are two ways to extend existing database adapters. Either by extending the base class or by adding functionality through hooks.

Classes

All modules also export anES6 class as<Name>Service that can be directly extended. See theService CLI guide on how to override existing and implement new methods.

Service methods

This section describes specifics on how theservice methods are implemented for all adapters.

constructor(options)

Initializes a new service. Should callsuper(options) when overwritten.

Methods without hooks

The database adapters support calling their service methods without any hooks by adding a_ in front of the method name as_find,_get,_create,_patch,_update and_remove. This can be useful if you need the raw data from the service and don't want to trigger any of its hooks.

js
// Call `get` without running any hooksconst message = await app.service('/messages')._get('<message id>')

note

These methods are only available internally on the server, not on the client side and only for the Feathers database adapters. They donot send any events.

adapter.find(params)

adapter.find(params) -> Promise returns a list of all records matching the query inparams.query using thecommon querying mechanism. Will either return an array with the results or a page object ifpagination is enabled.

ts
// Find all messages for user with id 1constmessages = await app.service('messages').find({  query: {    userId:1  }})console.log(messages)// Find all messages belonging to room 1 or 3constroomMessages = await app.service('messages').find({  query: {    roomId: {      $in: [1,3]    }  }})console.log(roomMessages)

Find all messages for user with id 1

GET /messages?userId=1

Find all messages belonging to room 1 or 3

GET /messages?roomId[$in]=1&roomId[$in]=3

adapter.get(id, params)

adapter.get(id, params) -> Promise retrieves a single record by its unique identifier (the field set in theid option during initialization).

ts
constmessage = await app.service('messages').get(1)console.log(message)
GET /messages/1

adapter.create(data, params)

adapter.create(data, params) -> Promise creates a new record withdata.data can also be an array to create multiple records.

ts
constmessage = await app.service('messages').create({  text:'A test message'})console.log(message)constmessages = await app.service('messages').create([  {    text:'Hi'  },  {    text:'How are you'  }])console.log(messages)
POST /messages{  "text": "A test message"}

adapter.update(id, data, params)

adapter.update(id, data, params) -> Promise completely replaces a single record identified byid withdata. Does not allow replacing multiple records (id can't benull).id can not be changed.

ts
constupdatedMessage = await app.service('messages').update(1, {  text:'Updates message'})console.log(updatedMessage)
PUT /messages/1{ "text": "Updated message" }

adapter.patch(id, data, params)

adapter.patch(id, data, params) -> Promise merges a record identified byid withdata.id can benull to allow replacing multiple records (all records that matchparams.query the same as in.find).id can not be changed.

ts
constpatchedMessage = await app.service('messages').patch(1, {  text:'A patched message'})console.log(patchedMessage)constparams = {  query: {read:false }}// Mark all unread messages as readconstmultiPatchedMessages = await app.service('messages').patch(  null,  {    read:true  },  params)
PATCH /messages/1{ "text": "A patched message" }

Mark all unread messages as read

PATCH /messages?read=false{ "read": true }

adapter.remove(id, params)

adapter.remove(id, params) -> Promise removes a record identified byid.id can benull to allow removing multiple records (all records that matchparams.query the same as in.find).

ts
constremovedMessage = await app.service('messages').remove(1)console.log(removedMessage)constparams = {  query: {read:true }}// Remove all read messagesconstremovedMessages = await app.service('messages').remove(null, params)
DELETE /messages/1

Remove all read messages

DELETE /messages?read=true

Released under the MIT License.

Copyright © 2012-2025 FeathersJS contributors


[8]ページ先頭

©2009-2025 Movatter.jp