Giter VIP home page Giter VIP logo

api-next's Introduction

api-next

Usage (example with mongoose)

Reduce boilerplate when creating crud endpoints Hooks are just middlewares that run before each of the handlers.

/pages/api/posts/[[...id]].ts

import getConfig from 'next/config'
import * as mongoose from 'mongoose'
import { createService, hook, NotFoundError } from 'api-next'

export interface PostAttrs {
  title: string
}

export interface PostDoc extends mongoose.Document {
  title: string
  likes: number
}

interface PostModel extends mongoose.Model<PostDoc> {
  build(attrs: PostAttrs): PostDoc
}

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    require: true,
  },
  likes: {
    type: Number,
    require: false,
    default: 0,
  },
})

const name = 'Post'

const Post = (mongoose.models[name] ||
  mongoose.model<PostDoc, PostModel>(name, postSchema)) as PostModel

// From express-validator
const validateBody = hook.validateRequest(({ body, query, cookies }) => [
  body('title').isString().notEmpty().withMessage('Title is required'),
])

const config = getConfig()

// Concept from Feathersjs: https://feathersjs.com/
const hooks = {
  before: {
    all: [
      hook.connectToDatabase({
        name: 'posts-db',
        connect: () =>
          mongoose.connect(config.serverRuntimeConfig.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true,
          }),
      }),
    ],
    create: [validateBody],
    update: [validateBody],
  },
}

// All the keys are optional
// Pick what you need
export default createService({
  hooks,
  find: async () => Post.find(),
  create: async (body: PostAttrs) => Post.build(body),
  get: async (pk) => Post.findById(pk),
  update: async (pk, body: PostAttrs) => {
    const post = await Post.findById(pk)
    if (!post) throw new NotFoundError()

    post.set(body)
    await post.save()
    return post
  },
  remove: async (pk) => {
    const post = await Post.findById(pk)
    if (!post) throw new NotFoundError()
    await post.remove()
    return { success: true, data: post }
  },
})

Alternative

import { createMongooseService } from 'api-next'

const { find, create, get, update, remove } = createMongooseService(Post)

export default createService({
  hooks,
  find,
  create,
  get,
  update,
  remove,
})

api-next's People

Contributors

flaviouk avatar renovate-bot avatar

Stargazers

Roman avatar

api-next's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @types/mongoose Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • Update actions/cache action to v4
  • Update actions/checkout action to v4
  • Update actions/setup-node action to v4
  • Update dependency @types/node to v20
  • Update dependency eslint-plugin-prettier to v5
  • Update dependency express-validator to v7
  • Update dependency husky to v9
  • Update dependency prettier to v3
  • Update dependency typescript to v5
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/main.yml
  • actions/checkout v2
  • actions/setup-node v1
  • actions/cache v1
npm
package.json
  • express-validator 6.6.1
  • morgan 1.10.0
  • node-mocks-http 1.8.1
  • simple-http-status 1.1.0
  • @types/mongoose 5.7.36
  • @types/morgan 1.9.1
  • @types/node 14.6.0
  • babel-jest 26.3.0
  • next 9.5.2
  • husky 4.2.5
  • prettier 2.0.5
  • eslint-plugin-prettier 3.1.4
  • tsdx 0.13.2
  • tslib 2.0.1
  • typescript 4.0.2
  • ts-jest 26.2.0
  • next >=9.5.2
  • node >=10

  • Check this box to trigger a request for Renovate to run again on this repository

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.