Giter Club home page Giter Club logo

adminjs-sequelizejs's Introduction

adminjs-sequelizejs

This is an official AdminJS adapter which integrates sequelize ORM into AdminJS.

Usage

The plugin can be registered using standard AdminJS.registerAdapter method.

const AdminJS = require('adminjs')
const AdminJSSequelize = require('@adminjs/sequelize')

AdminJS.registerAdapter(AdminJSSequelize)

More options can be found in AdminJS repository.

Testing

Integration tests require running database. Database connection data are given in config/config.js. Make sure you have following env variables set: POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_PORT, POSTGRES_DATABASE, POSTGRES_HOST. Take a look at config/config.js to see default values.

Than you will have to create database and run migrations

npm run sequelize db:create
npm run sequelize db:migrate

License

AdminJS is copyrighted © 2023 rst.software. It is a free software, and may be redistributed under the terms specified in the LICENSE file.

About rst.software

We’re an open, friendly team that helps clients from all over the world to transform their businesses and create astonishing products.

  • We are available for hire.
  • If you want to work for us - check out the career page.

adminjs-sequelizejs's People

Contributors

adamfrydrychrst avatar ariansobczak-rst avatar bakkerthehacker avatar bartoszhernas avatar brandonzacharie avatar danklewicz-swb avatar dependabot[bot] avatar domingo2000 avatar dziraf avatar elvisyang avatar etinin avatar frontkickit avatar jonaszjestem avatar jwasiak avatar leibowitz avatar matex1024 avatar puntonim avatar sbross avatar sdepold avatar semantic-release-bot avatar sewerynstarczyk avatar sureshvarman avatar t1nky avatar wojtek-krysiak 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adminjs-sequelizejs's Issues

Filters are not case insensitive

In previous versions of admin sequelizejs, filtering could be done using upper or lower case letters. This functionality no longer works in later versions of admin sequelizejs.

Instead of being able to find similar text that can ignore case, the exact case must be known when searching. This is problematic as searches that previously worked no longer work correctly, and additional work must be done to find the exact case of text when searching.

While this used to work in older versions, I also see that it was removed to be compatible with mysql. Compatibility is useful, but I don't feel like the existing features should be given up in this case.

Versions 1.2.1 and versions 2.0.0 are working correctly and do not have the problematic filtering. I would like to continue updating admin packages to receive new features and fixes, but for now will be stuck on these versions.

unordered database

I have a problem trying to populate the database because the order is reversed

i created the model Player_name, and Player_number
In mySQL database in order

  1. Player_name
  2. Player_number

but in adminpanel create, the order is reversed to

  1. Player_number
  2. Player_name

Postgres JSONB column is defaulted to an odd value in "new" action

Describe the bug
After updating admin-bro from 2.4.1 to 2.8.0 and admin-bro-sequelize from 0.4.0 to 0.5.1 there is an issue with JSONB fields when adding new resources via "new" action.

The default value described in Sequelize model id a JSON: { ".": "." }, but the record that's inserted into the database is set to [["."]] which causes issues when frontend expects an actual object.

Installed libraries and their versions

To Reproduce
Steps to reproduce the behavior:

  1. Create a Sequelize model with a JSONB field having a default value i. e. as described above ({ ".": "." }) and add the resource to AdminBro.
  2. Navigate to the resource in admin, press "New" and fill in required fields (note: the JSONB field is not a part of the form)
  3. Submit the form.
  4. Check what's actually inserted into the database, the value for JSONB field will be [["."]]

Expected behavior
The default value from Sequelize model is inserted, or an empty JSON object.

Not working with sqlite

When using sqlite for database API works fine, but loading the admin dashboard fails and the chrome console has the following errors:

design-system.bundle.js:223160 Uncaught TypeError: Cannot read property 'split' of undefined
    at NavigationElement (design-system.bundle.js:223160)
    at renderWithHooks (global.bundle.js:37614)
    at mountIndeterminateComponent (global.bundle.js:40293)
    at beginWork (global.bundle.js:41407)
    at HTMLUnknownElement.callCallback (global.bundle.js:22999)
    at Object.invokeGuardedCallbackDev (global.bundle.js:23048)
    at invokeGuardedCallback (global.bundle.js:23103)
    at beginWork$1 (global.bundle.js:46014)
    at performUnitOfWork (global.bundle.js:44968)
    at workLoopSync (global.bundle.js:44941)
global.bundle.js:42338 The above error occurred in the <NavigationElement> component:
    in NavigationElement (created by NavigationElementWrapper)
    in li (created by NavigationElementWrapper)
    in NavigationElementWrapper (created by Navigation)
    in ul (created by Navigation)
    in section (created by Styled(styled.section))
    in Styled(styled.section) (created by Navigation)
    in Navigation (created by SidebarResourceSectionOriginal)
    in SidebarResourceSectionOriginal (created by WrapperComponent)
    in WrapperComponent (created by Sidebar)
    in section (created by styled.section)
    in styled.section (created by Sidebar)
    in section (created by sidebar__StyledSidebar)
    in sidebar__StyledSidebar (created by Sidebar)
    in Sidebar (created by App)
    in section (created by styled.section)
    in styled.section (created by App)
    in App
    in Router (created by BrowserRouter)
    in BrowserRouter
    in Unknown
    in Provider

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
logCapturedError @ global.bundle.js:42338
global.bundle.js:45476 Uncaught TypeError: Cannot read property 'split' of undefined
    at NavigationElement (design-system.bundle.js:223160)
    at renderWithHooks (global.bundle.js:37614)
    at mountIndeterminateComponent (global.bundle.js:40293)
    at beginWork (global.bundle.js:41407)
    at HTMLUnknownElement.callCallback (global.bundle.js:22999)
    at Object.invokeGuardedCallbackDev (global.bundle.js:23048)
    at invokeGuardedCallback (global.bundle.js:23103)
    at beginWork$1 (global.bundle.js:46014)
    at performUnitOfWork (global.bundle.js:44968)
    at workLoopSync (global.bundle.js:44941)
DevTools failed to load SourceMap: Could not load content for chrome-extension://onimolfnbjjikjiialpfahffkjjgdgkh/content-detached.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
DevTools failed to load SourceMap: Could not load content for chrome-extension://onimolfnbjjikjiialpfahffkjjgdgkh/content-detached.css.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

Dashboard works fine with mysql, surely admin bro is agnostic to this all abstraction handled by sequelize?

Add support for nested objects

Mixed type in AdminBro.

In both jsonb and array fields:

const Painting = sequelize.define(
  'paintings',
  {
    id: {
      type: Sequelize.BIGINT,
      primaryKey: true,
      autoIncrement: true
    },
    title: {
      type: Sequelize.STRING
    },
    tags: {
      type: Sequelize.ARRAY({
        type: Sequelize.BIGINT,
        references: {
          model: Tag,
          key: 'id'
        }
      }),
    }
  })

SequelizeDatabaseError: column Provider.name does not exist

Describe the bug
Cannot sort of virtual columns. This is either a bug in sequlize or unsupported use case. I will be updating a similar issue is sequalize that appears to be related. sequelize/sequelize#10983

Installed libraries and their versions

"dependencies": {
    "admin-bro": "^2.2.12",
    "admin-bro-expressjs": "^2.0.5",
    "admin-bro-sequelizejs": "^0.4.1",
    "aws-sdk": "^2.666.0",
    "cron": "^1.7.2",
    "cron-parser": "^2.13.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "express-fileupload": "^1.1.7-alpha.3",
    "express-formidable": "^1.2.0",
    "fs-extra": "^8.1.0",
    "json2csv": "^4.5.4",
    "mirth-api": "^0.0.5",
    "moment": "^2.24.0",
    "morgan": "^1.10.0",
    "node-fetch": "^2.6.0",
    "nodemailer": "^6.3.1",
    "pg": "^7.14.0",
    "sequelize": "^5.21.2",
    "swagger-jsdoc": "^4.0.0",
    "vm2": "^3.8.4"
  }

To Reproduce
Steps to reproduce the behavior:

  1. Create a model with a virtual field, example
/* jshint indent: 1 */

module.exports = (sequelize, DataTypes) => {
    let Provider = sequelize.define('Provider',
        {
            nationalProviderIdentifier: {
                type: DataTypes.INTEGER,
                allowNull: false,
                unique: true
            },
            familyName: {
                type: DataTypes.STRING,
                allowNull: false
            },
            givenName: {
                type: DataTypes.STRING,
                allowNull: false
            },
            additionalName: {
                type: DataTypes.STRING,
                allowNull: false,
                defaultValue: ''
            },
            name: {
                // type: DataTypes.VIRTUAL(DataTypes.STRING, ['givenName', 'familyName', 'additionalName']),
                type: DataTypes.VIRTUAL,
                get: function() {
                    return `${this.getDataValue('givenName')} ${this.getDataValue('familyName')} ${this.getDataValue('additionalName')}`.trim()
                }
            },
        }
    )

    return Provider
}
  1. Open Admin Bro to the resource

Expected behavior
Throw an error to the effect of Cannot sort on VIRTUAL Datatype "${sortBy}"! You can provide a different sort by field to avoid this issue, see: https://adminbro.com/ResourceOptions.html#sort

Could sort by the primary key when the default sort by key is virtual but that could create an issue where it's not sorting as expect and the user has no clue why.

Additional context
Fix: https://github.com/SoftwareBrothers/admin-bro-sequelizejs/blob/master/src/resource.js

...
const { Op, DataTypes } = require('sequelize')
...
    const { direction, sortBy } = sort
    if (this.SequelizeModel.fieldRawAttributesMap[sortBy].type instanceof DataTypes.VIRTUAL) {
        throw new Error(`Cannot sort on VIRTUAL Datatype "${sortBy}" on resource "${this.SequelizeModel.name}"! You can provide a different sort by field to avoid this issue, see: https://adminbro.com/ResourceOptions.html#sort`)
    }
    const sequelizeObjects = await this.SequelizeModel
      .findAll({
        where: convertFilter(filter),
        limit,
        offset,
        order: [[sortBy, (direction || 'asc').toUpperCase()]],
      })

Error: There are no resources with given id: "[object Object]"

I am getting errors when dealing with foreign keys defined without a reference.

Let's assume there are two tables, Post and User

User

class User extends Model {
}
User.init({
        id: {
            type: DataTypes.INTEGER,
            field: 'id',
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: DataTypes.STRING,
            field: 'name',
            allowNull: false
        }
    }, {
        sequelize,
        schema: 'public',
        modelName: 'User',
        tableName: 'user',
        timestamps: false
    });

Post

Note the references is commented out. This is by design, and is just left there to highlight how it would be defined, if necessary.

    class Post extends Model {
    };
    Post.init({
        id: {
            type: DataTypes.INTEGER,
            field: 'id',
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        },
        user_id: {
            type: DataTypes.INTEGER,
            field: 'user_id',
//            references: {
//                model: 'user',
//                key: 'id'
//            },
//            onUpdate: 'NO ACTION',
//            onDelete: 'CASCADE',
            allowNull: false
        }
    }, {
        sequelize,
        schema: 'public',
        modelName: 'Post',
        tableName: 'post',
        timestamps: false
    })

Now we define a relationship, which is totally valid in sequelize even if the references property has not been defined.

            User.hasMany(Post, {
              as: 'posts',
              foreignKey: 'user_id'
            });

By doing this, the this.sequelizePath.references?.model in https://github.com/SoftwareBrothers/admin-bro-sequelizejs/blob/8e672b49095c1504782029ee4eb1d8fe9c1a61b4/src/property.ts#L76 is returning an object (even with the return ... as string

I'm using latest version (1.1.1) and I get this when showing what I get from property.reference()

{
  tableName: 'user',
  table: 'user',
  name: 'User',
  schema: 'public',
  delimiter: '.',
  toString: [Function: toString]
}

Which is similar to what addSchema is returning in sequelize, which is what Model.getTableName returns. And model is set to the value returned by getTableName. So the model property is not of type Model in that case.

And the full error:

Error: There are no resources with given id: "[object Object]"
This is the list of all registered resources you can use: ....

at AdminBro.findResource (node_modules/admin-bro/lib/admin-bro.js:249:13)
at ApiController.getActionContext (node_modules/admin-bro/lib/backend/controllers/api-controller.js:86:34)
at ApiController.resourceAction (node_modules/admin-bro/lib/backend/controllers/api-controller.js:129:38)
at handler (node_modules/@admin-bro/express/plugin.js:59:52)
at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
at next (node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
at node_modules/express/lib/router/index.js:281:22
at param (node_modules/express/lib/router/index.js:354:14)
at param (node_modules/express/lib/router/index.js:365:14)
at param (node_modules/express/lib/router/index.js:365:14)
at Function.process_params (node_modules/express/lib/router/index.js:410:3)
at next (node_modules/express/lib/router/index.js:275:10)
at node_modules/express-formidable/lib/middleware.js:36:7
at IncomingForm.<anonymous> (node_modules/formidable/lib/incoming_form.js:107:9)

sortBy is required in BaseResource.find [Sequelize]

Pretty minor issue, but took me a while to track down. When using BaseResource.find I get the following error unless I provide a sortBy option.

TypeError: Cannot read property '_modelAttribute' of undefined

I'm only using sequelize so unsure if it affects other databases.

Merge bugfix in v1.3.0-beta.5 to the rebranded version

The bug fix "use LIKE instead of ILIKE (020cebd)" in v1.3.0-beta.5 hasn't been included in the rebranded version. resource.find method isn't available with AdminJS using Sequelize because of this issue.

Could we release a new version to include this change ?

Does not include package main section

Does not include package.main section

  "main": "lib/index.js",

Cause error Cannot find module '@adminjs/sequelize' or its corresponding type declarations.ts(2307)

Cannot create a record whose PK isn't autoincrement

Hello there! I'm using adminJS together with sequelize, and I have to say, thanks for saving me from tedious admin code! ❤️

I have a country table with a countryCode PK that I'm not able to fill in using adminjs.

I understand it shouldn't be editable (it's a primary key after all) but I noticed that creating a new country resulted in a SQL query that didn't have a countryCode.

Here are the relevant bits of my Country model:

class Country extends Sequelize.Model {
  static init(sequelize, DataTypes) {
    return super.init(
      {
        countryCode: {
          type: DataTypes.CHAR(3),
          allowNull: false,
          primaryKey: true,
        },
        // ...
      },
      {
        // ...
        indexes: [
          {
            name: 'PRIMARY',
            unique: true,
            using: 'BTREE',
            fields: [{ name: 'countryCode' }],
          },
        ],
      }
    )
  }
}

After some digging, I noticed that in property.ts there is a isEditable function that returns false if the field is a primary key.

I fixed the issue using patch-package, by making isEditable not check isId during creation. The patch is below:


diff --git a/node_modules/@adminjs/sequelize/src/property.ts b/node_modules/@adminjs/sequelize/src/property.ts
index a135452..b586e15 100644
--- a/node_modules/@adminjs/sequelize/src/property.ts
+++ b/node_modules/@adminjs/sequelize/src/property.ts
@@ -43,14 +43,14 @@ class Property extends BaseProperty {
     return this.fieldName;
   }
 
-  isEditable(): boolean {
+  isEditable({ forCreate }: { forCreate?: boolean } = {}): boolean {
     if ((this.sequelizePath as any)._autoGenerated) {
       return false;
     }
     if (this.sequelizePath.autoIncrement) {
       return false;
     }
-    if (this.isId()) {
+    if (!forCreate && this.isId()) {
       return false;
     }
     return true;
diff --git a/node_modules/@adminjs/sequelize/src/resource.ts b/node_modules/@adminjs/sequelize/src/resource.ts
index e36a0e0..89562c1 100644
--- a/node_modules/@adminjs/sequelize/src/resource.ts
+++ b/node_modules/@adminjs/sequelize/src/resource.ts
@@ -156,7 +156,7 @@ class Resource extends BaseResource {
   }
 
   async create(params): Promise<Record<string, any>> {
-    const parsedParams = this.parseParams(params);
+    const parsedParams = this.parseParams(params, { forCreate: true });
     const unflattedParams = flat.unflatten<any, any>(parsedParams);
     try {
       const record = await this.SequelizeModel.create(unflattedParams);
@@ -215,7 +215,7 @@ class Resource extends BaseResource {
    *
    * @return  {Object}          converted params
    */
-  parseParams(params) {
+  parseParams(params, { forCreate }: { forCreate?: boolean } = {}) {
     const parsedParams = { ...params };
     this.properties().forEach((property) => {
       const value = parsedParams[property.name()];
@@ -224,7 +224,7 @@ class Resource extends BaseResource {
           delete parsedParams[property.name()];
         }
       }
-      if (!property.isEditable()) {
+      if (!property.isEditable({ forCreate })) {
         delete parsedParams[property.name()];
       }
     });

Request generates invalid query

"@admin-bro/express": "^3.0.1",
"@admin-bro/sequelize": "^1.1.1",
"admin-bro": "^3.3.1",
"connect-session-sequelize": "^7.0.4",
"express": "^4.17.1",
"express-formidable": "^1.2.0",
"express-session": "^1.17.1",
"sequelize": "^6.3.5"

Error: Invalid value Where {
  attribute: Fn { fn: 'LOWER', args: [ Col { col: 'users.nickname' } ] },
  comparator: '=',
  logic: { [Symbol(like)]: Fn { fn: 'LOWER', args: [ '%t%' ] } }
}
    at Object.escape (/home/viralforces_web/server/api/node_modules/sequelize/lib/sql-string.js:65:11)
    at PostgresQueryGenerator.escape (/home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:985:22)
    at PostgresQueryGenerator.whereItemQuery (/home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2356:102)
    at PostgresQueryGenerator.whereItemsQuery (/home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2250:23)
    at /home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2381:30
    at Array.map (<anonymous>)
    at PostgresQueryGenerator._whereGroupBind (/home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2380:21)
    at PostgresQueryGenerator.whereItemQuery (/home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2316:19)
    at /home/viralforces_web/server/api/node_modules/sequelize/lib/dialects/abstract/query-generator.js:2247:25
    at Array.forEach (<anonymous>)

I think it is produced by https://github.com/SoftwareBrothers/admin-bro-sequelizejs/blob/a8ab13b6b1c7985935824d907dd9cd1453d3620e/src/utils/convert-filter.ts#L23

Using MySQL-incompatible ILIKE comparison

Hey there!

I'm giving adminbro a try for the first time, and I'm loving it! However string filters aren't working. I dug a little deeper and found that it's using the ILIKE operator that's not present in MySQL.

Digging into the node_modules folder, and changing build/utils/convert-filter.js from Op.iLike to Op.like, fixes the crash (but doesn't perform a case insensitive search obviously).

Related: #5

When deploy the latest version to npmjs

Right now the latest version in npmjs is 5.0.1, it does not work well with the latest AdminBro on records filter. so when the latest version will be in npmjs?

Filtering by enum generates incorrect LIKE query

Filtering by enum generates incorrect LIKE query.

message: operator does not exist: enum_test_kind ~~ unknown, stack: SequelizeDatabaseError: operator does not exist: enum_test_kind ~~ unknown
WHERE ("test"."deletedAt" IS NULL AND "test"."kind" LIKE '%months%')

Cannot filter by uuid id: operator does not exist: uuid ~~* unknown

This was originally SoftwareBrothers/adminjs#932 . I was asked to create the issue here.

Describe the bug
Trying to filter a resource by it's primary key(id) which has type of uuid. When entering a full uuid in filter input and pressing apply, I get an error message in console:
SequelizeDatabaseError: operator does not exist: uuid ~~* unknown

Installed libraries and their versions

To Reproduce
Steps to reproduce the behavior:

  1. Go to a resource with uuid type primary key
  2. Try to filter the resource with said uuid primary key
  3. get the error

Expected behavior
I expect for the filtering to work correctly and give me the needed object

Additional context
Suspecting that this happens because the generate query has ILIKE operator in where clause for uuid
WHERE ("TABLE_NAME"."id" ILIKE '%3ad54072-c394-4020-b47e-c72dd29147a5%')

[Issue] Wrong column naming

When using aliases or underscored: true, code references with database column name instead aliases.

PR to fix this (tested):
#23

Resource show date with time instead of date only using Sequelize.DATEONLY

My model:

const MyModel = sequelize.define('my_model', {
    myDate: {
      type: DataTypes.DATEONLY,
      allowNull: false,
    },
  },
  ...
);
  return MyModel;
};

But the resource still show date with default time (7:00:00 AM) instead of date only.
Like this: 3/29/2020, 7:00:00 AM
The date field didn't prompt time, though.

I think this is an unexpected behaviour and should be fixed.

In the mean time, is there a way to manipulate myDate properties to show date only?

[DEP0128] DeprecationWarning: Invalid 'main' field

(node:20) [DEP0128] DeprecationWarning: Invalid 'main' field in '/usr/src/app/node_modules/@admin-bro/sequelize/package.json' of 'build/index.js'. Please either fix that or report it to the module author
at tryPackage (node:internal/modules/cjs/loader:364:15)
at Function.Module._findPath (node:internal/modules/cjs/loader:566:18)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object. (/usr/src/app/dist/admin/AdminBro.js:9:37)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object. (/usr/src/app/dist/server.js:54:31)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object. (/usr/src/app/dist/index.js:23:18)
at Module._compile (node:internal/modules/cjs/loader:1101:14)

Array relations is not working

I have 2 models which is related to each other.

Product.tsProductTranslation.ts
Product
|-- Id: number
|-- Price: number
|-- Translations: Array<ProductTranslation>
ProductTranslation
|-- LanguageId: string
|-- ProductId: Product
|-- Name: string

But I don't see translations array on create, edit or show page.

image

But when I check network traffic I see that there are already Translation fields responded from server.

image

I think the issue is related to sequelizejs adapter integration.

I want to achieve this structure:

image

Unhandled BOOLEAN type

Boolean mapping is missing in src/property.js
const TYPES_MAPPING = [ ['STRING', 'string'], ['TEXT', 'string'], ['INTEGER', 'number'], ['BIGINT', 'number'], ['FLOAT', 'float'], ['REAL', 'float'], ['DOUBLE', 'float'], ['DECIMAL', 'float'], ['DATE', 'datetime'], ['DATEONLY', 'date'], ['ENUM', 'string'], ['ARRAY', 'array'], ['JSON', 'object'], ['JSONB', 'object'], ['BLOB', 'string'], ['UUID', 'string'], ['CIDR', 'string'], ['INET', 'string'], ['MACADDR', 'string'], ['RANGE', 'string'], ['GEOMETRY', 'string'], ]
['BOOLEAN','boolean'] should be added to the list

Support for Sequelize v7

Hey there :)

Sequelize v7 is almost out of alpha and I was wondering if you have any plans to start supporting it already?

Unable to filter enum fields for multiple values

If I try a filtered URL like:

https://my.adminjs.server/admin/resources/myresource?filters.enumField=foo&filters.enumField=bar

The query only looks for WHERE enumField = 'foo'

This is because of line 16 in @adminjs/sequelize/lib/utils/convert-filter.js:

 if (property.sequelizePath.values || uuidRegex.test(value.toString())) {

Since it is an enum field, this intercepts before it gets to the check for isArray and returns an Op.eq where clause instead of an Op.in clause.

Can't handle Sequelize UniqueConstraintError

My model:

const Superuser = sequelize.define('superuser', {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
   ...
}

When I create new instance with existing email on admin bro dashboard, the debug console throw SequelizeUniqueConstraintError: Validation error and the loading on save button didn't stop. I want to prevent this error just like Sequelize ValidationError. Since UniqueConstraintError is subclass of ValidationError, I suggest change on resource.js on admin-bro-sequelizejs.

before:

if (error.name === SEQUELIZE_VALIDATION_ERROR) {
    throw this.createValidationError(error)
}

suggested:

const SequelizeValidationError = require('sequelize').ValidationError
...
if (error instanceof SequelizeValidationError) {
    throw this.createValidationError(error)
}

And all works just like ValidationError.

Can we get update on admin-bro-sequelizejs or is there something I can do to fix this? (either make PR or change something in my code to handle this).

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.