Coder Social home page Coder Social logo

adminjs-mikroorm's Introduction

adminjs-mikroorm

This is an official AdminJS adapter which integrates MikroORM into AdminJS.

Installation

yarn

$ yarn add @adminjs/mikroorm

npm

$ npm i @adminjs/mikroorm

Usage

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

import { Database, Resource } from '@adminjs/mikroorm';
import AdminJS from 'adminjs';
import { validate } from 'class-validator';

const setupAdminJs = async () => {
  const orm = await MikroORM.init({
    entities: [User],
    dbName: process.env.DATABASE_NAME,
    type: 'postgresql',
    clientUrl: process.env.DATABASE_URL,
  });

  // If your entities use `class-validator` to validate data, you can inject it's validate method into the resource.
  Resource.validate = validate;
  AdminJS.registerAdapter({ Database, Resource });

  // You can instantiate AdminJS either by specifying all resources separately:
  const adminJs = new AdminJS({
    resources: [{ resource: { model: User, orm }, options: {} }],
  });

  // Or by passing your ORM instance into `databases` property.
  const adminJs = new AdminJS({
    databases: [orm],
  });
  // You should choose to use either `resources` or `databases`
};

Example

An example project can be found in example-app directory.

Associations

Currently only ManyToOne and OneToOne relationships are supported due to current AdminJS's core limitations for adapter integrations. OneToMany and ManyToMany relationships can still be achieved through a combination of custom components and hooks.

Contribution

Running the example app

If you want to set this up locally this is the suggested process:

  1. Fork the repo
  2. Install dependencies
yarn install
  1. Register this package as a linked package
yarn link
  1. Setup example app

Install all dependencies and use previously linked version of @adminjs/mikroorm.

cd example-app
yarn install
yarn link "@adminjs/mikroorm"

Optionally you might want to link your local version of adminjs package

  1. Make sure you have all the envs set (see ./example-app/example.env and create an .env file based on that)

  2. Build the package in watch mode

(in the root folder)

yarn dev
  1. Run the app in the dev mode
cd example-app
yarn dev

Pull request

Before you make a PR make sure all tests pass and your code wont causes linter errors. You can do this by running:

yarn lint
yarn test

Make sure you have an .env file in project's root directory for the test runner to use:

DATABASE_URL=postgres://postgres:@localhost:5433/mikroorm_test
DATABASE_NAME=mikroorm_test

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-mikroorm's People

Contributors

adamfrydrychrst avatar ariansobczak-rst avatar corbt avatar dziraf avatar rubiin avatar semantic-release-bot avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

adminjs-mikroorm's Issues

Define UUID type for id column

Hi,

I am receiving an error while searching for entities by their id (uuid type column, postgres, using Mikro ORM =>v5.2).

The generated database query when filtering for IDs is

select "o0".* from "organization" as "o0" where "o0"."id" like '%9d6c5def-4a9b-4deb-8d38-6a5ae473edaa%' order by "o0"."id" asc limit 10 - operator does not exist: uuid ~~ unknown

So apparently adminjs thinks the id columns represented as uuids are strings and uses the like operator.

Is there any fix for this?
Thank you for your help.

Best!

1:1 relation with "eager: true" not showing up as reference

Description
I have a couple of entities defined which have a 1:1 relation:

@Entity()
export class User extends BaseEntity<User, 'id'> {
  @PrimaryKey()
  id!: number;

  @Property()
  @Index()
  name!: string;

  @OneToOne(() => NotificationPreferences, (preferences) => preferences.user, {
    ref: true,
    eager: true,
    orphanRemoval: true,
  })
  notificationPreferences!: Ref<NotificationPreferences>;
}

@Entity()
export class NotificationPreferences extends BaseEntity<
  NotificationPreferences,
  'id'
> {
  @PrimaryKey()
  id!: number;

  @Property()
  frequency!: string;

  @OneToOne(() => User, (user) => user.notificationPreferences, {
    ref: true,
    owner: true,
  })
  user!: Ref<User>;
}

When I navigate to the "User" resource in AdminJS and select a user, the "Notification Preferences" field is blank. However, if I navigate to the "Notification Preferences" resource, I can see the linked user. After some experimenting, I've found that I can get it to work by removing the eager: true option from the notificationPreferences reference on the User entity.

Installed libraries
"@adminjs/express": "^5.0.1",
"@adminjs/mikroorm": "^2.0.0",
"@adminjs/nestjs": "^5.1.0",
"@mikro-orm/core": "^5.6.0",
"@mikro-orm/nestjs": "^5.1.2",
"@mikro-orm/postgresql": "^5.6.0",

Additional details
Here is the JSON response from the request to /admin/api/resources/User/records/1/show with the eager: true option set:

{
  "params": {
    "id": 1,
    "name": "Admin Use",
    "notificationPreferences.id": 1,
    "notificationPreferences.frequency": "every",
    "notificationPreferences.lastEmailDate": null,
    "notificationPreferences.user": 1
  },
  "populated": {
    "musician": { ...data }
  },
  "baseError": null,
  "errors": {},
  "id": 1,
  "title": "Admin Use",
  "recordActions": [ ...data ],
  "bulkActions": []
}

And without the eager: true option set (this works):

{
  "params": {
    "id": 1,
    "name": "Admin Use",
    "notificationPreferences": 1
  },
  "populated": {
    "notificationPreferences": { ...data },
    "musician": { ...data }
  },
  "baseError": null,
  "errors": {},
  "id": 1,
  "title": "Admin Use",
  "recordActions": [ ...data ],
  "bulkActions": []
}

OneToMany Relationship

Hello,

I have an entity called Artwork that has an OneToMany relationship with another entity ArtworkImage. I read in the doc that OneToMany relationship can still be achieved through custom components and hooks. What exactly does it mean here? Can you give me an example?

I am setting up AdminJS with Fastify and Mikroorm

No adapters found with nestjs

Hi I am using mikroorm with nestjs like this:

AdminModule.createAdminAsync({
			inject: [MikroORM],
      useFactory: (orm:MikroORM) => ({
        adminJsOptions: {
          rootPath: '/admin',
          resources: [{ resource: User, orm }],
        }
      })
    }),

Running the app shows the following error

(node:195520) UnhandledPromiseRejectionWarning: NoResourceAdapterError: There are no adapters supporting one of the resource you provided

Unhandled type warnigns

Describe the bug
We can see a lot of unhandled type warnigns in the terminal output on load of any resource in the admin panel.

Installed libraries and their versions
"@adminjs/express": "^4.1.0"
"@adminjs/mikroorm": "^1.1.0"
"@adminjs/nestjs": "^4.0.0"
"@mikro-orm/core": "^5.0.5"

To Reproduce
Steps to reproduce the behavior:

  1. Login
  2. Click on resource

Expected behavior
No unhandled type warning.

Screenshots
That's the console output.

Unhandled type: string
Unhandled type: string
Unhandled type: Date
Unhandled type: Date
Unhandled type: Date
Unhandled type: Date
Unhandled type: string
Unhandled type: string
Unhandled type: object
Unhandled type: object
Unhandled type: string
Unhandled type: string
Unhandled type: string
Unhandled type: string
Unhandled type: string
Unhandled type: string
Unhandled type: Date
Unhandled type: Date
Unhandled type: Date

AdminJSOptions with schema

@Entity({ customRepository: () => UserRepository })
export class User extends OmputBaseEntity {
  [EntityRepositoryType]?: UserRepository;

  @Property({ unique: true, columnType: 'varchar(255)' })
  @IsEmail()
  email: string;

  @Property({ hidden: true, columnType: 'varchar(255)' })
  password: ComparablePassword;

  @Property({ nullable: true })
  age?: number;

}

Desktop (please complete the following information if relevant):

  • OS: Macos Monterey
  • Browser Chrome
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.
That's our module setup using Nestjs.

AdminModule.createAdminAsync({
      inject: [MikroORM],
      useFactory: async (orm: MikroORM) => {
        return {
          adminJsOptions: {
            rootPath: '/admin',
            resources: [
              {
                resource: {
                  model: User,
                  orm,
                },
              }
            ]
          }
        };
      }
    }),

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.