W
W
Wasya UK2018-07-09 22:40:06
Node.js
Wasya UK, 2018-07-09 22:40:06

Whether it is correct to make out routing so?

I'm trying to learn how to correctly write a backend server on a node, but I'm not very sure if it's possible to draw up the code in this style? I will be glad to any remarks.

const router = require('express').Router();
const mongoose = require('mongoose');

// Project model
const Project = require('../models/project');

// @routes
router
  .route('/:id')
  .all((req, res, next) => {
    if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
      next(new Error(404, "Wrong project id"));
    } else {
      next();
    }
  })
  .get((req, res, next) => {
    Project.findById(req.params.id)
      .then(project => res.json(project));
  })
  .put((req, res, next) => {
    Project.findByIdAndUpdate(req.params.id, req.body, { new: true })
      .then(project => res.json(project));
  })
  .delete((req, res, next) => {
    Project.findByIdAndRemove(req.params.id)
      .then(project => res.json(project));
  })
  .post((req, res, next) => {
    next(new Error("not implemented!"));
  });

router.get('/', (req, res, next) => {
  Project.find()
    .sort({ date: -1 })
    .then(projects => res.json(projects))
    .catch(next);
});

router.post('/', (req, res, next) => {
    const newProject = new Project({
      name: req.body.name,
      description: req.body.description,
      slides: []
    });

    newProject
      .save()
      .then(project => res.json(project))
      .catch(next);
  });

module.exports = router;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anubis, 2018-07-10
@Anubis

I prefer to keep the express/koa application instance, router instance, and routes in separate files.

  • router.js
    import Router from 'koa-router';
    
    export const router = new Router();

  • routes/index.js
    import './example';
    import './another-route';
    import './one-more-route';

  • routes/example.js
    import { router } from '../../router';
    
    router.get('/example', (ctx) => {
        ctx.body = { yo: 'Yo dude' };
    });
    
    router.post('/example', (ctx) => {
        ctx.body = { wow: 'Some POST request goes here' };
    });

  • app.js
    import Koa from 'koa';
    
    import { router } from './router';
    import './routes';
    
    const app = new Koa();
    // body parser etc
    // app.use(someMiddleware());
    // app.use(moreMiddleware());
    app.use(router.routes(), router.allowedMethods());
    
    app.listen(8000);

D
Damir Rysaev, 2018-07-09
@freepad

It is better to move the request processing code to a separate place.

const mongoose = require('mongoose');

const api = {};

api.checkId = () => (req, res, next) =>  {
    if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
        next(new Error(404, "Wrong project id"));
    } else {
        next();
    }
};

api.get = (Project) => (req, res, next) => {
    Project.findById(req.params.id)
        .then(project => res.json(project));
};

api.update = (Project) => (req, res, next) => {
    Project.findByIdAndUpdate(req.params.id, req.body, { new: true })
        .then(project => res.json(project));
};

api.delete = (Project) => (req, res, next) => {
    Project.findByIdAndRemove(req.params.id)
        .then(project => res.json(project));
};

api.notImplement = () => (req, res, next) => {
    next(new Error("not implemented!"));
};

api.all = (Project) => (req, res, next) => {
    Project.find()
        .sort({ date: -1 })
        .then(projects => res.json(projects))
        .catch(next);
};

api.create = (Project) => (req, res, next) => {
    const newProject = new Project({
        name: req.body.name,
        description: req.body.description,
        slides: []
    });

    newProject
        .save()
        .then(project => res.json(project))
        .catch(next);
};

module.exports = api;

const router = require('express').Router();
const api = require('../api/project')

// Project model
const Project = require('../models/project');

// @routes
router
    .route('/:id')
    .all(api.checkId())
    .get(api.get(Project))
    .put(api.update(Project))
    .delete(api.delete(Project))
    .post(api.notImplement());

router.get('/', api.all(Project));

router.post('/', api.create(Project));

module.exports = router;

UPD:
I also think it’s better to return errors to the server if you don’t plan to process them somehow later:
res.status(404).json({message: 'Project not found'}).end()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question