使用 MikroORM 和 AdminJS
安装
¥Installation
要将 MikroORM 与 AdminJS 一起使用,你需要安装:
¥To use MikroORM with AdminJS you need to install:
$ yarn add adminjs
$ yarn add @adminjs/mikroorm
# A MikroORM driver and core package, choose the one which suits you:
$ yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
$ yarn add @mikro-orm/core @mikro-orm/mysql # for mysql
$ yarn add @mikro-orm/core @mikro-orm/mariadb # for mariadb
$ yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
$ yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
-
特定于你服务器框架的插件:
¥A plugin specific to your server's framework:
$ yarn add @adminjs/express
# Peer dependencies
$ yarn add express express-formidable express-session
$ yarn add @adminjs/hapi
# Peer dependencies
$ yarn add @hapi/boom @hapi/cookie @hapi/hapi @hapi/inert
设置
¥Setup
安装过程完成后,我们需要设置 AdminJS 端点和数据库连接。该过程很简单,但根据你使用的 plugin
而有所不同。下面你可以找到特定于受支持框架的示例:
¥Once the installation process is completed, we need to set up AdminJS endpoints and database connection. The process is straightforward but differs based on which plugin
you are using. Below you can find examples specific to supported frameworks:
MikroORM + Express 插件
¥MikroORM + Express Plugin
import AdminJS from 'adminjs';
import { Database, Resource } from '@adminjs/mikroorm';
import AdminJSExpress from '@adminjs/express';
import { MikroORM } from '@mikro-orm/postgresql';
import { validate } from 'class-validator'; // optional
const PORT = process.env.PORT ?? 3000;
const run = async () => {
/* Initialize MikroORM like you would do normally, you can also import your MikroORM instance from a separate file */
const orm = await MikroORM.init({
entities: [User, Car, Seller], // use your own entities
dbName: process.env.DATABASE_NAME,
clientUrl: process.env.DATABASE_URL,
});
/* Optional: if you're using class-validator, assign it to Resource */
Resource.validate = validate;
/* Tell AdminJS which adapter to use */
AdminJS.registerAdapter({ Database, Resource });
const app = express();
/* Create AdminJS instance */
const admin = new AdminJS({
databases: [orm],
});
const router = AdminJSExpress.buildRouter(admin);
app.use(admin.options.rootPath, router);
app.listen(PORT, () => {
console.log(`App listening at http://localhost:${PORT}`);
});
}
run();
MikroORM + Hapi 插件
¥MikroORM + Hapi Plugin
import AdminJS from 'adminjs';
import { Database, Resource } from '@adminjs/mikroorm';
import AdminJSHapi from '@adminjs/hapi';
import { MikroORM } from '@mikro-orm/postgresql';
import { validate } from 'class-validator'; // optional
const PORT = process.env.PORT ?? 3000;
const run = async () => {
/* Initialize MikroORM like you would do normally, you can also import your MikroORM instance from a separate file */
const orm = await MikroORM.init({
entities: [User, Car, Seller], // use your own entities
dbName: process.env.DATABASE_NAME,
clientUrl: process.env.DATABASE_URL,
});
/* Optional: if you're using class-validator, assign it to Resource */
Resource.validate = validate;
/* Tell AdminJS which adapter to use */
AdminJS.registerAdapter({ Database, Resource });
const server = Hapi.server({ port: PORT })
/* Configure AdminJS */
const adminOptions = {
databases: [orm],
};
/* Register AdminJS as a Hapi server's plugin */
await server.register({
plugin: AdminJSHapi,
options: adminOptions,
});
await server.start();
console.log(`App listening at ${server.info.uri}`);
}
run();
你可以随后启动服务器,管理面板将在 http://localhost:{PORT}/admin
处可用。如果你完全遵循示例设置,你应该能够在侧边栏中看到所有实体,并且应该能够对它们执行基本的 CRUD 操作。
¥You can start your server afterwards and the admin panel will be available at http://localhost:{PORT}/admin
. If you followed the example setup thoroughly, you should be able to see all of your entities in the sidebar, and you should be able to perform basic CRUD operations on them.
要进一步自定义你的 AdminJS 面板,请参阅 official documentation
。
¥To further customize your AdminJS panel, please refer to the official documentation
.
身份验证
¥Authentication
上面的示例设置了具有未经身份验证访问的 AdminJS。要要求你的用户在访问管理面板之前进行身份验证,需要进行一些特定于插件的修改:
¥The examples above set up AdminJS with unauthenticated access. To require your users to authenticate before accessing the admin panel, some plugin-specific modifications are required:
Express
你需要使用 AdminJSExpress.buildAuthenticatedRouter
而不是 AdminJS.buildRouter
:
¥You need to use AdminJSExpress.buildAuthenticatedRouter
instead of AdminJS.buildRouter
:
之前:
¥Before:
const router = AdminJSExpress.buildRouter(admin);
之后:
¥After:
const ADMIN_EMAIL = 'example@test.com';
const ADMIN_PASSWORD = 'password';
const router = AdminJSExpress.buildAuthenticatedRouter(admin, {
authenticate: async (email, password) => {
/* Your code for verifying email & password goes here */
return email === ADMIN_EMAIL && password === ADMIN_PASSWORD
? { email } // the function should return an object containing user's data if authenticated successfully
: null;
},
cookiePassword: process.env.COOKIE_PASSWORD ?? 'makesurepasswordissecure',
});
Hapi
你只需将 auth
属性添加到 AdminJS 选项即可。
¥You need to simply add auth
property to AdminJS options.
之前:
¥Before:
const adminOptions = {
databases: [orm],
};
之后:
¥After:
const ADMIN_EMAIL = 'example@test.com';
const ADMIN_PASSWORD = 'password';
const adminOptions = {
databases: [orm],
auth: {
authenticate: async (email, password) => {
/* Your code for verifying email & password goes here */
return email === ADMIN_EMAIL && password === ADMIN_PASSWORD
? { email } // the function should return an object containing user's data if authenticated successfully
: null;
},
strategy: 'session',
cookiePassword: process.env.COOKIE_PASSWORD ?? 'makesurepasswordissecure',
isSecure: false, // only https requests
},
};
示例
¥Example
可以在 此处 中找到使用 MikroORM 和 AdminJS 的示例应用
¥An example app using MikroORM with AdminJS can be found here