Giter VIP home page Giter VIP logo

autorestfulprisma's Introduction

autoRestfulPrisma

Simple and easy to use automated MVC-like REST API backend built using Express, and Prisma as the model.

You could say it's the continuation of my old repo.

Installation

  1. Clone this repo.
git clone https://github.com/itsfaqih/autoRestfulPrisma.git
cd autoRestfulPrisma
npm install
  1. Setup database configuration.
cp ./prisma/.env.example ./prisma/.env

Change the DATABASE_URL to your database URL, and the provider in schema.prisma datasource. You can see more detailed guides here.

or you could just try it quick using the populated demo database (the dev.db) without changing any configuration.

  1. Introspect the database with Prisma
npx prisma introspect
  1. Generate Prisma Client
npx prisma generate

Usage

Repository

// src/repositories/UserRepository.ts (you can create your own)
import ResourceRepository from '../cores/resources/ResourceRepository' // REST boilerplate repository

class UserRepository extends ResourceRepository { // or extend Repository
  constructor() {
    super()
    this.setModel(this.prisma.users) // Set the model
  }

  async findByEmail(email: string) { // Create your own custom method
    try {
      return await this.model.findOne({
        where: {
          email
        }
      })
    } catch (error) {
      throw error
    } finally {
      await this.prisma.disconnect()
    }
  }
}

export default UserRepository

Controller

// src/controllers/UserController.ts (you can create your own)
import ResourceController from '../cores/resources/ResourceController' // REST boilerplate controller
import UserRepository from '../repositories/UserRepository'

class UserController extends ResourceController { // or extend Controller
  constructor() {
    super(new UserRepository()) // Pass the repository
  }

  async whoseEmail(req: Request, res: Response) { // Create your own custom method
    try {
      const user = await this.repository.findByEmail(req.query.email)

      if (user != null) {
        res.send({ data: user })
      } else {
        res.send({ data: null })
      }
    } catch (error) {
      res.status(400).send({ error: error.message })
    }
  }
}

export default UserController

Route

// src/routes.ts
// Import the controller
import UserController from './controllers/UserController'

module.exports = [
  {
    endpoint: '/users', // Set the endpoint url
    resource: true, // Set it true if it's REST controller
    controller: new UserController() // initialize the controller
  },
  {
    endpoint: '/whose_email', // Custom endpoint
    controller: (new UserController()).whoseEmail // Select the handler,
    method: 'GET' // Select the HTTP Method, it's GET by default
  }
]

If you're using the Resource, it will generate all restful endpoints as follows:

GET /users (get all user data)
POST /users (create new user)
GET /users/:id (get one user data)
PUT /users/:id (update user data)
DELETE /users/:id (delete user data)

NB: id parameter is using "id" field by default.

Using Scaffolding

You can also generate the Controller, Repository, and Route automatically using cli.

node ./scaffolds/cli make:rest <Entity> <Table>:optional

For example:

# Generate UserController, UserRepository, and /users endpoint
node ./scaffolds/cli User users 

# Generate BookController, BookRepository, and /book endpoint
node ./scaffolds/cli Book 

Run the REST API Server

The server will run at port 3000 by default

npm run dev

autorestfulprisma's People

Contributors

itsfaqih avatar

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.