API REST con Mangosta

API REST con Mangosta

En el servidor de API REST, una petición de cada uno del extremo delantero tienen operaciones de base de datos backend correspondiente.

Por ejemplo, en respuesta a GETuna solicitud de búsqueda de datos en la base de datos: Con el fin de terminar el procesamiento GETpetición de un cliente de GETla solicitud, significa que los intentos cliente para acceder al servidor para recuperar los datos, por lo tanto, para ser procesados por un número de servicio expreso, entonces usted necesita para realizar la lógica de negocio en la operación de consulta de base de datos; iniciar una consulta, recuperar un conjunto de documentos de la base de datos y luego se convierte en el mensaje de respuesta se envía de vuelta al servidor.

Por lo tanto, la solicitud de respuesta de final de proceso implica dos partes, una lógica de negocio, parte interactúan con la base de datos.

Mira POSTsolicitud:

POSTSolicitud de información mediante la solicitud, somática Express Server después del tratamiento, una solicitud de inicio correspondiente createsolicitud a MongoDB, la createsolicitud será en una base de datos collectionpara crear una nueva document, y almacena el cuerpo de la petición de la información procesada en el mismo. Por último, los resultados de la operación a la parte posterior respuesta al cliente.

Por lo tanto, para la ejecución de cualquier operación final de la API REST, ya sea GET, PUT, POST o DELETE, comenzará a las operaciones de bases de datos correspondientes en el fondo. Es decir, HTTP cliente recibe las solicitudes de la API REST deben asignarse a una base de datos correspondientes operaciones.

cambiodishRouter.js

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')

const Dishes = require('../models/dishes')

const dishRouter = express.Router()

dishRouter.use(bodyParser.json())

dishRouter.route('/')
.get((req, res, next) => {
    Dishes.find({})
    .then((dishes) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(dishes)
    }, (err) => next(err))
    .catch((err) => next(err))
})
.post((req, res, next) => {
    Dishes.create(req.body)
    .then((dish) => {
        console.log('Dish Created ', dish)
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(dish)
    }, (err) => next(err))
    .catch((err) => next(err))
})
.put((req, res, next) => {
    res.statusCode = 403
    res.end('PUT operation not supported on /dishes')
})
.delete((req, res, next) => {
    Dishes.reomve({})
    .then((resp) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(resp)
    }, (err) => next(err))
    .catch((err) => next(err))
})

dishRouter.route('/:dishId')
.get((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(dish)
    }, (err) => next(err))
    .catch((err) => next(err))
})
.post((req, res, next) => {
    res.statusCode = 403
    res.end('POST operation not supported on /dishes/' + req.params.dishId)
})
.put((req, res, next) => {
    res.statusCode = 200
    Dishes.findByIdAndUpdate(req.params.dishId, {
        $set: req.body
    }, {
        new: true	// 返回改变后的document
    })
    .then((dish) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(dish)
    }, (err) => next(err))
    .catch((err) => next(err))
})
.delete((req, res, next) => {
    Dishes.findByIdAndRemove(req.params.dishId)
    .then((resp) => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json')
        res.json(resp)
    }, (err) => next(err))
    .catch((err) => next(err))
})

dishRouter.route('/:dishId/comments')
.get((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null) {
            res.statusCode = 200
            res.setHeader('Content-Type', 'application/json')
            res.json(dish.comments)
        } else {
            err = new Error('Dish' + req.params.dishId + ' not found')
            err.status = 404
            return next(err)
        }
    }, (err) => next(err))
    .catch((err) => next(err))
})
.post((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null) {
            dish.comments.push(req.body)
            dish.save()
            .then((dish) => {
            	res.statusCode = 200
                res.setHeader('Content-Type', 'application/json')
                res.json(dish)    
            }, (err) => next(err))
        } else {
            err = new Error('Dish ' + req.params.dishId + ' not found')
            err.status = 404
            return next(err)
        }
    }, (err) => next(err))
    .catch((err) => next(err))
})
.put((req, res, next) => {
    res.statusCode = 403
    res.end('PUT operation not supported on /dishes/' + req.params.dishId + '/comments')
})
.delete((erq, res next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null) {
            for (let i = (dish.comments.length - 1); i >= 0; i--) {
                dish.comments.id(dish.comments[i]._id).remove()
            }
            dish.save()
            .then((dish) => {
                res.statusCode = 200
                res.setHeader('Content-Type', 'application/json')
                res.json(dish)
            }, (err) => next(err))
        } else {
            err = new Error('Dish ' + req.params.dishId + ' not found')
            err.status = 404
            return next(err)
        }
    }, (err) => next(err))
    .catch((err) => next(err))
})

dishRouter.route('/:dishId/comments/:commentId')
.get((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null && dish.comments.id(req.params.commentId) != null) {
        	res.statusCode = 200
            res.setHeader('Content-Type', 'application/json')
            res.json(dish.comments.id(req.params.commentId))
        } else if(dish == null) {
            err = new Error('Dish ' + req.params.dishId + ' not found')
            err.statusCode = 404
            return next(err)
        } else {
            err = new Error('Comment ' + req.params.commentId + ' not found')
            res.statusCode = 404
            return next(err)
        }
    }, (err) => next(err))
    .catch((err) => next(err))
})
.post((req, res, next) => {
    res.statusCode = 403
    res.end('POST operation not supported on /dishes/' + req.params.dishId + '/comments/' + req.params.commentId)
})
.put((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null && dish.comments.id(req.params.commentId) != null) {
      		if (req.body.rating) {
                dish.comments.id(req.params.commentId).rating = req.body.rating
            }
            if (req.body.comment) {
                dish.comments.id(req.params.commentId).comment = req.body.comment
            }
            dish.save()
            .then((dish) => {
                res.statusCode = 200
                res.setHeader('Content-Type', 'application/json')
                res.json(dish)
            }, (err) => next(err))
        } else if (dish == null) {
            err = new Error('Dish ' + req.params.commentId + ' not found')
            err.statusCode = 404
            return next(err)
        }  else {
            err = new Error('Comment ' + req.params.commentId + ' not found');
            err.status = 404;
            return next(err);            
        }
    }, (err) => next(err))
    .catch((err) => next(err));
})
.delete((req, res, next) => {
    Dishes.findById(req.params.dishId)
    .then((dish) => {
        if (dish != null && dish.comments.id(req.params.commentId) != null) {
            dish.comments.id(req.params.commentId).remove()
            dish.save()
            .then((dish) => {
                res.statusCode = 200
                res.setHeader('Content-Type', 'application/json');
                res.json(dish)             
            }, (err) => next(err))
        } else if (dish == null) {
            err = new Error('Dish ' + req.params.dishId + ' not found');
            err.status = 404
            return next(err)
        } else {
            err = new Error('Comment ' + req.params.commentId + ' not found');
            err.status = 404
            return next(err)         
        }
    }, (err) => next(err))
    .catch((err) => next(err))
})

module.exports = dishRouter

res.send(), res.json(), res.end()La diferencia

Supongo que te gusta

Origin www.cnblogs.com/wydumn/p/12590663.html
Recomendado
Clasificación