Giter Site home page Giter Site logo

typeorm-json-api's Introduction

why this lib

this is a generic web api router which can CRUD(create, read, update, delete) any TypeOrm entities

- query records: get /api/repos/yourEntity 
- query by id: get /api/repos/yourEntity/:id
- add a records: post /api/repos/yourEntity
- modify a record: put /api/repos/yourEntity/:id
- delete a records: /api/repos/yourEntity/:id

with query parameters, the get/read api supports

  • pagination
  • filter on each field
  • order on each field

support role based authorization, if you want some entity only accessed by admin role, simply add

@Entity()
@Authorize({role:'admin'}
export class User {
    @PrimaryGeneratedColumn()
    id: number
}

you can also add authorization to specific operations, for example you want common use only be able to delete his how post,

@Authorize({role:'common', operation:'delete', columns:['userId']})

query parameters usage

suppose you have a entity user as following:

{id:number, firstName:number, lastName:number}

get /api/repos/user

if the client request the api without parameter, the api will return all users

get api/repos/user?s=3&c=2

  • key 's' - how many records should skip
  • key 'c' - how many records should return
  • so this example skips the first 3 records, takes 2 records:

get api/repos/user?firstName=a

  • the key firstName means field name
  • 'a' and 'd' are two reserved values, 'a' means order by user asc, 'd' means order by user desc
  • so this example return all users, order by firstName asc

api/repos/user?firstName=*Joe

  • query the users whose firstName contains 'Joe',
firstName like '%Joe%'

api/repos/user?firstName=Joe

  • query the users whose firstName exactly match 'Joe'
firstName = 'Joe'

api/repos/user?id=2~4

  • find user id range from 2 to 4
firstName between (2,4)

api/repos/user?id=2~

  • find user id >= 2

api/repos/user?id=~4

  • find user id <= 4

installation

if you are starting a new project,

you can clone https://github.com/jaikechen/typeorm-json-api/tree/master/src/app as an starter.

if you want add this lib to an exists project

  1. install the typeorm and express and this package
npm i express  @types/express --save
npm i typeorm sqlite reflect-metadata --save
npm i typeorm-json-api
  1. add your typeorm configuration
 export const ormConfig = {
  "type": "sqlite",
  "database": "db.sqlite",
  "entities": [
    "src/entities/*.ts"
  ],
  "logging": false,
  "synchronize": true
}
  1. add an entity to /src/entities, e.g. user.ts
import {Entity, Column, PrimaryGeneratedColumn} from "typeorm";
@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;
    @Column()
    firstName: string;
    @Column()
    lastName: string;
}

add router

import {createCRUDRouter} from 'typeorm-json-api'
const app = express()
...
app.use('/api/repos', createCRUDRouter(ormConfig))

log

the second parameter of createCRUDRouter is a callback function to log CRUD request

default log

createCRUDRouter(ormConfig)
or
createCRUDRouter(ormConfig, undefined)

disable log

createCRUDRouter(ormConfig,null)

customze log

createCRUDRouter(ormConfig,(level,msg)=>{
  /* your own log code*/ 
  })

authorization

the third parameter of createCRUDRouter is the verifyToken handler,

app.use('/api/repos', createCRUDRouter(ormConfig, undefined,verifyToken))

the following is a very simple version of verify token handler

const secret = 'very secret'
function getToken(req: Request, res: Response) {
    const token = jwt.sign({ username: '[email protected]' }, secret, { expiresIn: '1800s' })
    res.send(token)
}
function verifyToken(req, res, next) {
    console.log('in verify token')
    const authHeader = req.headers['authorization']
    const token = authHeader && authHeader.split(' ')[1]
    if (token == null) {
        return res.sendStatus(401)
    }
    jwt.verify(token, secret, (err: any, user: any) => {
        if (err) {
            return res.sendStatus(403)
        }
        req.user = user
        next() // pass the execution off to whatever request the client intended
    })
}

typeorm-json-api's People

Contributors

fluent-cms avatar

Watchers

 avatar

typeorm-json-api's Issues

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.