5.1.1 • Published 5 days ago

fastify-mongoose-rest v5.1.1

Weekly downloads
1
License
MIT
Repository
github
Last release
5 days ago

Fastify Mongoose Rest

npm npm GitHub install size npm bundle size npm type definitions

Table of Contents

Features

  • Creates a set of RESTful Fastify routes of a Mongoose model for common CRUD operations.
    • Listing / Searching documents
    • Details of a document
    • Inserting a document
    • Modifying a document
    • Deleting a document
    • Inserting multiple documents at once
  • Automatically adds tags, summary, and description for Open API documentation using Fastify Swagger.
  • Validates the request body using Fastify Schema supplied in the form of a JSON Schema.
  • Pagination support with page and pageSize parameters.

Installing

Using npm:

$ npm install fastify-mongoose-rest

Using yarn:

$ yarn add fastify-mongoose-rest

Once the package is installed, you can import the library in using import or require:

import FastifyMongooseRest from 'fastify-mongoose-rest';

Or using require:

const FastifyMongooseRest = require('fastify-mongoose-rest');

Example

Basic usage:

/* src/models/cat.js */
import mongoose from 'mongoose';

const catSchema = mongoose.Schema({
  name: String,
  age: Number,
  color: String,
});

export default mongoose.model('Cat', catSchema);

/* src/routes/cats.js */
import Cat from '../models/cat';
import FastifyMongooseRest from 'fastify-mongoose-rest';

const catFastify = FastifyMongooseRest('cats', Cat);

export default function (fastify) {
  // GET /cats
  fastify.route(catFastify.list);
  // POST /cats/search
  fastify.route(catFastify.search);
  // GET /cats/:id
  fastify.route(catFastify.details);
  // POST /cats
  fastify.route(catFastify.create);
  // PATCH /cats/:id
  fastify.route(catFastify.modify);
  // DELETE /cats/:id
  fastify.route(catFastify.delete);
  // POST /cats/insert-many
  fastify.route(catFastify.insertMany);
}

Basic usage with options:

/* src/models/cat.js */
import mongoose from 'mongoose';

const catSchema = mongoose.Schema({
  registratin: {
    type: String,
    required: true,
    unique: true,
  },
  name: String,
  age: Number,
  color: String,
});

export default mongoose.model('Cat', catSchema);

/* src/routes/cats.js */
import Cat from '../models/cat';
import FastifyMongooseRest from 'fastify-mongoose-rest';

const catValidationSchema = {
  registration: {type: 'string'},
  name: {type: 'string'},
  age: {type: 'number'},
  color: {type: 'string'},
};

const catFastify = FastifyMongooseRest('cats', Cat, {
  validationSchema: catValidationSchema,
  tags: ['cats'],
  findProperty: 'registration',
});

export default function (fastify) {
  fastify.route(catFastify.list);
}

Each of the route objects return a partial Fastify route object, so you can add any other Fastify route options or override existing ones by merging the objects:

/* src/routes/cats.js */
import Cat from '../models/cat';
import FastifyMongooseRest from 'fastify-mongoose-rest';

const catValidationSchema = {
  name: {type: 'string'},
  age: {type: 'number'},
  color: {type: 'string'},
};

const catFastify = FastifyMongooseRest('cats', Cat, {
  validationSchema: catValidationSchema,
});

export default function (fastify) {
  fastify.route({
    ...catFastify.list,
    schema: {
      ...catFastify.list.schema,
      summary: 'List all cats',
      description: 'List all cats',
    },
  });
}

Initialization

Basic initialization:

import Cat from '../models/cat';
import FastifyMongooseRest from 'fastify-mongoose-rest';

const catFastify = FastifyMongooseRest('cats', Cat);

Adding routes

// No changes
fastify.route(catFastify.list);

// With changes
fastify.route({
  ...catFastify.list,
  schema: {
    ...catFastify.list.schema,
    summary: 'List all cats',
    description: 'List all cats',
  },
});

FastifyMongooseRestOptions

These are the available configuration options for the FastifyMongooseRest function:

{
  // `validationSchema` is the schema properties that will be used for validation in create and modify routes
  // It will also be used to validate returned documents in details, list, and search routes
  // In the same way this will also change how the output of OpenAPI documentation will look like
  // This is an optional property
  validationSchema: {
    name: { type: 'string' },
    age: { type: 'number' },
    color: { type: 'string' },
  },

  // `tags` is the tags that will be used for Open API documentation
  // This is an optional property
  tags: ['cats'],

  // By setting this property, instead of querying by `_id`, the query will be done by the property specified here
  // This will affect details, delete, and modify operations which use :id as a route parameter
  // This is an optional property
  findProperty: 'userId',
}

Operations

Create

The create operation will insert a new document into the database. Uses the validation schema to validate the request body.

Delete

The delete operator will delete a document from the database based on the :id route parameter of the request.

The field used for the query can be changed by setting the findProperty option in the options object. The default value is _id.

Details

The details operation will return a single document from the database based on the :id route parameter of the request.

The field used for the query can be changed by setting the findProperty option in the options object. The default value is _id.

Modify

The modify operation will modify a document from the database based on the :id route parameter of the request. Uses the validation schema to validate the request body.

The field used for the query can be changed by setting the findProperty option in the options object. The default value is _id.

List

The list operation will return a list of documents from the database based on the search parameters from the query string of the request.

Same as the search operation but with query parameters instead of a request body.

Given the total count parameter is set to true, the response will also include the total count of documents that match the search parameters in the X-Total-Count header.

Search

The search operation will return a list of documents from the database based on the search parameters from the body of the request.

Same as the list operation but with a request body instead of query parameters.

Given the total count parameter is set to true, the response will also include the total count of documents that match the search parameters in the X-Total-Count header.

Insert many

The insert many operation will insert multiple documents into the database. Uses the validation schema to validate the request body.

Search parameters

The search parameters are supplied in the request body for search operation or as query parameters in the request URL depending for list operation.

query

The query takes a object as an value that can be either a JSON object from the body, or a stringified JSON object from query string or body.

Default value is {}.

Example:

{"query":{"name": "Kitty","age":2}}

or

{"query":"{\"name\":\"Kitty\",\"age\":2}"}

More information: https://mongoosejs.com/docs/api/model.html#Model.find()

q

q is an alias for query.

{"q":{"name":"Kitty","age":2,}}

populate

populate takes a string, an object, or and array as a value. The object or array can be either in JSON format in the body, or in a stringified JSON format in query string or body.

By default no population is done.

Examples:

{"populate":"owner"}
{"populate":{"path":"owner"}}
{"populate":"{\"path\":\"owner\"}"}
{"populate":[{"path":"owner"},{"path":"children"}]}
{"populate":"[{\"path\":\"owner\"},{\"path\":\"children\"}]"}

More information: https://mongoosejs.com/docs/populate.html

projection

projection takes a string or an object as a value. The object can be either a JSON object from the body, or a stringified JSON object from query string or body.

The string can be formatted either as a comma separated list or a space separated list.

By default no projection is done.

Examples:

{"projection":"name"}
{"projection":"name,age"}
{"projection":"name age"}
{"projection":{"name":1}}
{"projection":"{\"name\":1}"}

More information: https://mongoosejs.com/docs/api/query.html#Query.prototype.projection()

select

select takes a string or an object as a value. The object can be either a JSON object from the body, or a stringified JSON object from query string or body.

The string can be formatted either as a comma separated list or a space separated list.

By default no selection is done.

Examples:

{"select":"name"}
{"select":"name,age"}
{"select":"name age"}
{"select":{"name":1}}
{"select":"{\"name\":1}"}

More information: https://mongoosejs.com/docs/api/query.html#Query.prototype.select()

sort

sort takes a string or an object as a value. The object can be either a JSON object from the body, or a stringified JSON object from query string or body.

The string can be formatted either as a comma separated list or a space separated list.

By default no sorting is done.

Examples:

{"sort":"name"}
{"sort":"name,-age"}
{"sort":"name -age"}
{"sort":{"name":1}}
{"sort":"{\"name\":1}"}

More information: https://mongoosejs.com/docs/api/query.html#Query.prototype.sort()

skip

skip takes a number as a value.

The skip parameter is ignored if page or pageSize parameters are supplied.

By default no documents are skipped.

Examples:

{"skip":10}

More information: https://mongoosejs.com/docs/api/query.html#Query.prototype.skip()

limit

limit takes a number as a value.

The limit parameter is ignored if page or pageSize parameters are supplied.

By default no documents are limited.

Examples:

{"limit":10}

More information: https://mongoosejs.com/docs/api/query.html#Query.prototype.limit()

page

page takes a positive number as a value.

The page parameter is used to calculate the skip parameter with the pageSize parameter. Note that this calculation will start from 0.

The formula is skip = page * pageSize. So if page was 1 and pageSize was 10, then skip would be 10 and it would skip the first 10 documents.

By default the page is 0 if pageSize is supplied or if the supplied value is less than 0.

Examples:

{"page":1}

p

p is an alias for page.

{"p":1}

pageSize

pageSize takes a positive number as a value.

The pageSize parameter is used to calculate the skip parameter with the page parameter.

The formula is skip = page * pageSize. So if page was 1 and pageSize was 10, then skip would be 10 and it would skip the first 10 documents.

By default the pageSize is 100 if page is supplied or if the supplied value is less than 1.

Examples:

{"pageSize":100}

Total count parameter

totalCount takes a boolean as a value. If set to true, the response will also include the total count of documents that match the search parameters in the X-Total-Count header.

This parameter is available for both list and search operations.

Include the parameter in the payload of the request body for search operation or as a query parameter in the request URL for list operation.

TypeScript

This library is written in TypeScript and comes with its own type definitions.

Credits

This library is inspired by restify-mongoose and is meant to be a replacement for it to be used with Fastify.

License

MIT

5.1.1

5 days ago

5.1.0

2 months ago

5.0.0

6 months ago

4.3.1

11 months ago

4.3.0

1 year ago

4.2.2

2 years ago

4.1.0

2 years ago

3.0.0

2 years ago

4.0.0

2 years ago

2.4.1

2 years ago

2.3.0

2 years ago

2.2.0

2 years ago

2.4.0

2 years ago

2.1.1

3 years ago

2.1.0

3 years ago

2.0.7

3 years ago

2.0.5

3 years ago

2.0.6

3 years ago

2.0.3

3 years ago

2.0.2

3 years ago

2.0.4

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago