Giter VIP home page Giter VIP logo

express-crud-router's Introduction

express-crud-router

codecov CircleCI

Expose resource CRUD (Create Read Update Delete) routes in your Express app. Compatible with React Admin Simple Rest Data Provider. The lib is ORM agnostic. List of existing ORM connectors.

import crud from 'express-crud-router'

app.use(
  crud('/admin/users', {
    get: ({ filter, limit, offset, order }) =>
      User.findAndCountAll({ limit, offset, order, where: filter }),
    create: body => User.create(body),
    update: (id, body) => User.update(body, { where: { id } }),
    destroy: id => User.destroy({ where: { id } }),
  })
)

Note: Content-Range header

For getList methods, the response includes the total number of items in the collection in X-Total-Count header. You should use this response header for pagination and avoid using Content-Range header if your request does not include a Range header. Checkout this stackoverflow thread for more info.

If you are using ra-data-simple-rest, please refer to the documentation to use X-Total-Count for pagination.

Install

npm install express-crud-router

Usage

Simple use case

import express from 'express'
import crud from 'express-crud-router'
import sequelizeCrud from 'express-crud-router-sequelize-v6-connector'
import { User } from './models'

const app = new express()
app.use(crud('/admin/users', sequelizeCrud(User)))

Limit actions

import express from 'express'
import crud from 'express-crud-router'
import sequelizeCrud from 'express-crud-router-sequelize-v6-connector'
import { User } from './models'

const app = new express()
app.use(
  crud('/admin/users', {
    ...sequelizeCrud(User),
    destroy: null,
  })
)

Custom filters

Custom filters such as case insensitive filter can be perform like this:

import express from 'express'
import { Op } from 'sequelize'
import crud from 'express-crud-router'
import sequelizeCrud from 'express-crud-router-sequelize-v6-connector'
import { User } from './models'

const app = new express()
app.use(
  crud('/admin/users', sequelizeCrud(User), {
    filters: {
      email: value => ({
        email: {
          [Op.iLike]: value,
        },
      }),
    },
  })
)

Custom filter handlers can be asynchronous. It makes it possible to filter based on properties of a related record. For example if we consider a blog database schema where posts are related to categories, one can filter posts by category name thanks to the following filter:

crud('/admin/posts', actions, {
  filters: {
    categoryName: async value => {
      const category = await Category.findOne({ name: value }).orFail()

      return {
        categoryId: category.id,
      }
    },
  },
})

Notes:

  • the filter key (here categoryName) won't be passed to the underlying action handler.
  • there is no support of conflicting attributes. In the following code, one filter will override the effect of the other filter. There is no garantee on which filter will be prefered.
crud('/admin/posts', actions, {
  filters: {
    key1: async value => ({
      conflictingKey: 'hello',
    }),
    key2: async value => ({
      conflictingKey: 'world',
    }),
  },
})

Additional attributes

Additional attributes can be populated in the read views. For example one can add a count of related records like this:

crud('/admin/categories', actions, {
  additionalAttributes: {
    postsCount: category => Post.count({ categoryId: category.id })
  },
  additionalAttributesConcurrency: 10 // 10 queries Post.count will be perform at the same time
})

additionalAttributes function parameters are:

  • the current row
  • an object: {rows, req} where rows are all page rows and req is the express request.

Similarly to how react-admin deals with resource references, express-crud-router provides additional field helpers:

  • populateReference
  • populateReferenceMany
  • populateReferenceManyCount
  • populateReferenceOne

Using additionalAttributes with populateReferenceManyCount or populateReferenceOne can be useful instead of using react-admin ReferenceManyCount and ReferenceOne as they are often used in list views and generate one HTTP query per row.

crud<number, { id: number }>('/users', {
  get: jest.fn().mockResolvedValue({
    rows: [{ id: 1 }, { id: 2 } , { id: 3 }],
    count: 2
  }),
}, {
  additionalAttributes: {
    posts: populateReferenceMany({
      fetchAll: async () => [
        {id: 10, authorId: 1},
        {id: 11, authorId: 1},
        {id: 12, authorId: 2},
      ],
      target: 'authorId'
    })
  }
})

Custom behavior & other ORMs

import express from 'express'
import crud from 'express-crud-router'
import { User } from './models'

const app = new express()
app.use(
  crud('/admin/users', {
    get: ({ filter, limit, offset, order }, { req, res }) =>
      User.findAndCountAll({ limit, offset, order, where: filter }),
    create: (body, { req, res }) => User.create(body),
    update: (id, body, { req, res }) => User.update(body, { where: { id } }),
    destroy: (id, { req, res }) => User.destroy({ where: { id } }),
  })
)

An ORM connector is a lib exposing an object of following shape:

interface Actions<R> {
  get: GetList<R> = (conf: {
    filter: Record<string, any>
    limit: number
    offset: number
    order: Array<[string, string]>
  }) => Promise<{ rows: R[]; count: number }>
  create: (body: R) => Promise<R & { id: number | string }>
  destroy: (id: string) => Promise<any>
  update: (id: string, data: R) => Promise<any>
}

Search

Autocomplete

When using react-admin autocomplete reference field, a request is done to the API with a q filter. Thus, when using the autocomplete field in react-admin, you must specify the behavior to search the records. This could looks like:

app.use(
  crud('/admin/users', , sequelizeCrud(User), {
    filters: {
      q: q => ({
          [Op.or]: [
            { address: { [Op.iLike]: `${q}%` } },
            { zipCode: { [Op.iLike]: `${q}%` } },
            { city: { [Op.iLike]: `${q}%` } },
          ],
        }),
    },
  })
)

express-crud-router ORM connectors might expose some search behaviors.

Recipies

Generic filter on related record attributes

crud('/admin/posts', actions, {
  filters: {
    category: async categoryFilters => {
      const categories = await Category.find(categoryFilters)

      return {
        categoryId: categories.map(category => category.id),
      }
    },
  },
})

This code allows to perform queries such as:

/admin/posts?filter={"category": {"name": "recipies"}}

Contribute

This lib uses semantic-release. You need to write your commits following this nomenclature:

  • feat: A new feature
  • fix: A bug fix
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code (white-space, - formatting, missing semi-colons, etc)
  • refactor: A code change that neither fixes a bug nor adds a feature
  • perf: A code change that improves performance
  • test: Adding missing or correcting existing tests
  • chore: Changes to the build process or auxiliary tools and libraries such as documentation generation

To trigger a major version release write in the core of the commit message:

feat: my commit

BREAKING CHANGE: detail here

Thanks

Thank you to Lalilo who made this library live.

express-crud-router's People

Contributors

cooperat avatar dependabot[bot] avatar gregdtd avatar hugomartinet avatar jaynetics avatar lucasff avatar naitokenzo avatar nicgirault avatar samuelnjenga avatar stonarini avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

express-crud-router's Issues

RA v3 is expecting X-TOTAL-COUNT header

From RA v3 - I get the following error:
The X-Total-Count header is missing in the HTTP Response. The jsonServer Data Provider expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?

Server side, I've enabled CORS to expose the header, but doesn't seem like your package is adding it to the getList and getManyReference actions - required/specified in this doc:
https://github.com/marmelab/react-admin/blob/master/packages/ra-data-json-server/README.md#rest-dialect

Am I missing something or is this something you need to add?

Big thanks - and promising package.

Update id - ra.notification.data_provider_error

Hello,

Thanks for creating this library! Helps a lot.

I've noticed that update function doesn't return id field which triggers ra.notification.data_provider_error with the following message:
The response to 'update' must be like { data: { id: 123, ... } }, but the received data does not have an 'id' key. The dataProvider is probably wrong for 'update'

It seems that update function is not compatible with ra-data-simple-rest stated here: React-Admin Data Providers

Replacing line with:

res.json({ id: (await doUpdate(req.params.id, req.body))[0] });

resolved issue for me.

Please let me know what you think.
Thanks!

Option to let express-sequelize-crud act as middleware?

First of all thanks for a lot for express-sequelize-crud <3

And I am wondering if it's possible to let express-sequelize-crud act as middleware?

So instead of:

async (req, res, next) => {
    ...
    res.json(rows);
}

I would like it to do something like this:

async (req, res, next) => {
    ...
    res.bodyInterface.setData(rows);
    next();
}

So I can do other stuff like logging after express-sequelize-crud did his thing.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Adding a middleware function before sequelize call

Hi there

I was wondering if you've thought about adding an option to allow users to provide a middleware function. For instance a permission check on a given route.

import authCheck from './authCheck';
const ROLES = ['ROLE_1', 'ROLE_2']

express.Router()
    .get('/some/resource', authCheck(ROLES), (req, res, next) => {})

As far as I can see there is no ability to add any validator or permission-checking middleware.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

sequelizeCrud wrong typing

`const insertStandardTag: Create<number, StandardTag> = (
parameters: StandardTag
) => {
return StandardTag.create(parameters)
}

adminRouter.use(
crud('/standard-tags', {
...sequelizeCrud(StandardTag),
create: insertStandardTag,
update: null,
getOne: null,
})
)`

This code produce the following issue:

Type 'Create<number, StandardTag>' is not assignable to type 'Create<number, unknown>'.
Types of parameters 'body' and 'body' are incompatible.
Type 'unknown' is not assignable to type 'StandardTag'.

The issue might be link to the following todo

Allow access to express request response (req/res) objects?

I have some auth middleware which sets an auth interface to the express request object.

I would like to be able to get access to the auth interface in my "Custom behavior", so I can do something like this:

router.use(crud('/machines', {
    ...sequelizeCrud(Machine),
    getList: ({ filter, limit, offset, order, req, res }) => { 
        return Machine.findAndCountAll({
            limit,
            offset,
            order,
            where: {
                ...filter,
                userId: req.auth.getAuthenticatedUser().id,
            }
        })
    }
}));

Custom primary key - not 'id'

Nice library. Thanks for that. I notice that if we define a custom primary key, some part of the library breaks due to assumption that an 'id' column exists.

I took a look at the code - for example in the getList flow, there is this method parseQuery() which makes the assumption of using ['id', 'ASC'] if an order option is not present.

Can someone fix this? Or point me in the right direction - in case I can help. Thanks in advance.

Missing importing p-limit?

I'm trying to deploy to AWS Lambda an application that uses express-crud-router, but I'm getting an error stating it cannot find the p-limit module. I see it being used on the following file, but I don't see a reference to p-limit on package.json. Doesn't it have to be imported on package.json?

import pLimit from 'p-limit';

model.findAndCountAll is not a function

Hi,
I got this error while trying to access API.

model.findAndCountAll is not a function
TypeError: model.findAndCountAll is not a function
    at getList (/Users/user/Documents/GitHub/jantungku/node_modules/express-sequelize-crud/lib/sequelize/index.js:27:20)
    at /Users/user/Documents/GitHub/jantungku/node_modules/express-sequelize-crud/lib/getList/index.js:32:17
    at Layer.handle [as handle_request] (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/layer.js:95:5)
    at /Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/user/Documents/GitHub/jantungku/node_modules/express/lib/router/index.js:275:10)
    at jsonParser (/Users/user/Documents/GitHub/jantungku/node_modules/express-sequelize-crud/node_modules/body-parser/lib/types/json.js:110:7)

FYI, my dependencies are:

"dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "express-sequelize-crud": "^6.1.2",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1",
    "mysql2": "^2.2.5",
    "sequelize": "^6.3.5",
    "sequelize-auto": "^0.7.6"
  }

My code:

var { crud, sequelizeCrud } = require('express-sequelize-crud');
var patients = require('./models/patients');

app.use(crud('/admin/patients', sequelizeCrud(patients)))

Thank you for your help!

when updating entry, update gets effective only when deleting another item

I am running in a strange bug:

  • i can see lists of items
  • i can delete items
  • i can add items
    when i edit an item, the Update is not realized in the database.
    if i delete another item, the Update statement is being progressed by the database (and i can see it in the log).

I think there is either a problem with my postgres config (running on Google Cloud SQL) in terms of autocommit or sth. else, but i have checked that with no result, or there is something wrong with a not returned promise in this adapter code?

The requested module 'express-sequelize-crud' does not provide an export named 'sequelizeCrud'

When I try to run the project with just bare minimum code, I am getting the below error. (Node - 13.1400, npm - 6.14.4)

F:\Freelance\seq-crud-1>node --experimental-modules index.js
file:///F:/Freelance/seq-crud-1/index.js:3
import crud, { sequelizeCrud } from 'express-sequelize-crud'
               ^^^^^^^^^^^^^
SyntaxError: The requested module 'express-sequelize-crud' does not provide an export named 'sequelizeCrud'

Code :

import express from 'express'
import crud, { sequelizeCrud } from 'express-sequelize-crud'
const Role = require('./models')

const app = new express()
app.use(crud('/admin/users', sequelizeCrud(Role)))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.