Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

api-next

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

api-next

## Usage (example with mongoose)

  • 1.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
12
Maintainers
1
Weekly downloads
 
Created
Source

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,
})

FAQs

Package last updated on 26 Oct 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc