Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ import express from 'express'
import Plugin from '@adminjs/express'
import Adapter, { Database, Resource } from '@adminjs/sql'

Resource.validate = async (tableName, params)=> {
// ...code
if(errors.length > 0){
return errors
}
return []
}

AdminJS.registerAdapter({
Database,
Resource,
Expand Down
27 changes: 27 additions & 0 deletions src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Filter,
ParamsType,
SupportedDatabasesType,
ValidationError,
} from 'adminjs';
import type { Knex } from 'knex';

Expand All @@ -22,6 +23,8 @@ export class Resource extends BaseResource {
return r;
}

public static validate: any;

private knex: Knex;

private dialect: DatabaseDialect;
Expand Down Expand Up @@ -127,6 +130,9 @@ export class Resource extends BaseResource {
const knex = this.schemaName
? this.knex(this.tableName).withSchema(this.schemaName)
: this.knex(this.tableName);

await Resource.validateObject(this.tableName, params);

await knex.insert(params);

return params;
Expand All @@ -140,6 +146,8 @@ export class Resource extends BaseResource {
? this.knex.withSchema(this.schemaName)
: this.knex;

await Resource.validateObject(this.tableName, params);

await knex.from(this.tableName).update(params).where(this.idColumn, id);

const knexQb = this.schemaName
Expand Down Expand Up @@ -187,4 +195,23 @@ export class Resource extends BaseResource {

return q;
}

static async validateObject(tableName: string, object: Record<string, any>): Promise<void> {
if (Resource.validate) {
const errors = await Resource.validate(tableName, object);
if (errors && errors.length) {
const validationErrors = errors.reduce(
(memo, error) => ({
...memo,
[error.property]: {
type: Object.keys(error.constraints)[0],
message: Object.values(error.constraints)[0],
},
}),
{},
);
throw new ValidationError(validationErrors);
}
}
}
}