npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

obrigado-react-admin-backend-utils

v1.3.8

Published

Helper utilities for react-admin graphql backend.

Downloads

62

Readme

Set of helpers for React Admin
To speed up admin panel development use obrigado frontend helpers

Requirments

  • Typeorm
  • Typegraphql
  • bcrypt (if you are goind to use auth )

Installation

Install package:

npm install obrigado-react-admin-backend-utils

or

yarn add obrigado-react-admin-backend-utils

Authorization setup

If want to use default auth

  1. Configure typeorm:
    Add path to entities:
    node_modules/obrigado-react-admin-backend-utils/dist/models/*.js
    example:
entities: ['app/database/models/*.ts',
'node_modules/obrigado-react-admin-backend-utils/dist/models/*.js'] 
  1. Add path to migrations:
    node_modules/obrigado-react-admin-backend-utils/dist/migrations/*.js
    example:
  migrations:[ 'app/database/migrations/*.ts',
  'node_modules/obrigado-react-admin-backend-utils/dist/migrations/*.js'], 
  1. Add helpers to server config
import {
    getAdministratorData,
} from 'obrigado-react-admin-backend-utils'
import { AdminDataResolver } from 'obrigado-react-admin-backend-utils/dist/resolvers/AdminDataResolver'
import { AdminAuthResolver } from 'obrigado-react-admin-backend-utils/dist/resolvers/AdminAuthResolver'
...
   const schema = await buildSchema({
        resolvers: [
            __dirname + '/graphql/resolvers/*.ts',
            __dirname + '/graphql/resolvers/admin/*.ts',
            AdminAuthResolver,AdminDataResolver //  <---
        ],
        authChecker,
    })
     const server = new ApolloServer({
        schema: schema,
        cors: {
            credentials: true,
            origin: function(origin, callback) {
                callback(null, true)
            },
        },
        context: async (session: any) => {
            return {
                session,
                user: getUserInfo(session.req),
                ...getAdministratorData(session.req), // <----
            }
        },
    })
  1. Add admin user checks to auth checker
import { AuthChecker } from 'type-graphql'
import { authCheckerAdmin } from 'obrigado-react-admin-backend-utils'

export const authChecker: AuthChecker<any> = (
    { root, args, context, info },
    roles
) => {
    // Verify admin user permissions
    if (authCheckerAdmin({ root, args, context, info }, roles)) {
        return true
    }
    if (!context.user && !context.administrator) return false

    if (!roles || roles.length == 0) {
        return true
    }

    return roles.includes(context.user.type)
}

Generating resolvers for your entities

The obrigado-react-admin-backend-utils package allows you to automatically create all necessary resolvers for React Admin with the help of createBaseCrudResolver function. It takes your GraphQL object and input types and TypeORM entity as arguments.

Let's say you want to create a User entity in your project. You will need to create an object GraphQL type (GraphQLModelClass) that will be used for information output:

import { Field, Int, ObjectType } from 'type-graphql'

@ObjectType('User')
export class UserGraphQL {
    @Field(type => Int)
    id: number
    @Field(type => Text)
    email: string
    @Field(type => Text, { nullable: true })
    token: string
}

You also need to create an input GraphQL type (GraphQLInputClass) that describes incoming data:

import { Field, InputType, Text } from 'type-graphql'

@InputType('UserInput')
export class UserGraphQLInput {
    @Field(type => Text)
    email: string
    @Field(type => Text)
    password: string
}

Finally, create a TypeORM entity (TypeORMEntityClass) that describes how User is stored in your database:

import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm'

@Entity('users')
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number
    @Column()
    email: string
    @Column()
    password: string
}

Now you can call createBaseCrudResolver(GraphQLModelClass, GraphQLInputClass, TypeORMEntityClass) to generate resolver class for User entity:

import { Resolver } from 'type-graphql'
import { createAdminResolver } from 'obrigado-react-admin-backend-utils'
import { UserGraphQL } from '../graphql/UserGraphQL'
import { UserGraphQLInput } from "../graphql/UserGraphQLInput"
import { User } from '../models/UserEntity'

const UserBaseResolver == createAdminResolver(
                            {
                                entity:User,
                                return:UserGraphQL,
                                create:UserGraphQLInput,
                            }) 
@Resolver()
export class _UserResolver extends UserBaseResolver {}

This will generate a resolver with following graphql mutation and queries:

  • adminUserGetList
  • adminUserGetOne
  • adminUserCreate
  • adminUserUpdate
  • adminUserUpdateMany
  • adminUserGetManyReference
  • adminUserDelete
  • adminUserDeleteMany

createAdminResolver config params

| param | required |description | |---|---|------| | entity | yes | TypeOrm entity class| | return | yes | TypeGraphQL ObjectType returned by getList,getOne,getMany| | create | yes | TypeGraphQL InputType param for create | | update | no | TypeGraphQL InputType param for update, if not specified create is used| | name | no | string name part of generated method, if not specified entity name is used. Example: admin[Name]UpdateMany |updateHelperOptions| no| UpdateHelper options : {ignore,fileHandler}. ignore: string[] - list of fields to ignore. fileHandler - handler class for files processing|

Overriding AdminResolver methods

createAdminResolver generates class with the following methods | definitions methods| implementation methods| |--------------------|-----------------------| | getListQuery | getList | | getOneQuery | getOne | | getManyQuery | getMany | | getManyReferenceQuery| getManyReference | | createMutation | create | | updateMutation | update | | updateManyMutation | updateMany | | deleteMutation | delete | | deleteManyMutation | deleteMany |

"Defenition" methods calls implementations methods with same params and contains only typegraphql decorators. So if you want to override logic override implementation methods (most of your cases):

const UserBaseResolver == createAdminResolver(
                            {
                                entity:User,
                                return:UserGraphQL,
                                create:UserGraphQLInput,
                            }) 
@Resolver()
export class _UserResolver extends UserBaseResolver {
            async getList( params: GQLReactAdminListParams,  context:any){
            // your logic 
            }
}

As you can see you don't need to put typegraphl decorators. If want to override method name in graphql, auth logic etc, then you need to override definition method:

 export class _UserResolver extends UserBaseResolver {
        @Authorized('admin')
         @Query(type =>UserList, {
             name: `adminUserList`,
         })
         async getListQuery(
             @Arg('params', type => GQLReactAdminListParams)
                 params: GQLReactAdminListParams,
             @Ctx() context:any
         ) {
             return this.getList(params,context)
         }
          
 }

if you want to alter filtering login in getList you don't need to override whole method, just override alterGetListQuery

Entities with file handling

If you want your entity to handle files as well you can pass options with File Handler to createBaseCrudResolver as a last argument.

You can find more on how to configure available File Handlers here:

Creating or re-defining resolver methods in AdminsResolvers

You can re-define existing methods in AdminAuthResolver and AdminDataResolver to implement you own authentication logic. AdminAuthResolver and AdminDataResolver have the following methods:

  • adminLogin
  • adminCheck
  • adminLogOut
  • update
  • create

By default admin is authorized by JWT token that is saved in cookies.

Roles & permissions

You can define roles and permissions in RoleConfig. Pass an array of objects containing roles and arrays with permissions to initialize it.

import {RoleConfig} from 'obrigado-react-admin-backend-utils'
const roles:Array<Role>=[
    {name: 'admin', permissions: ['create administrators', 'edit administrators']},
    {name: 'moderator', permissions: ['edit something']},
    {name: 'user', permissions: ['view something']}
    ]
RoleConfig.init(roles)    

If the admin's role is not specified RoleConfig will assign them the first role of the array ("amdin" role by default).

The following resolvers are available in AdminDataResolver:

  • getRoles (returns a list of all existing roles);
  • permissions (returns an array of admin's permissions);
  • role (returns admin's role).