Sharing routes on express

Asked

Viewed 77 times

1

I’m trying to make a generic controller that will provide the basic crud routes, the idea is to extend this controller and be able to add some custom routes that are only inherent in that class.

Following example:

export default class BaseController {

constructor(model, key) {
    this.model = model;
    this.modelName = model.modelName.toLowerCase();
    this.key = key;
}

route() {
    const router = new Router();

    router.get("/", (req, res) => {
      this
        .list()
        .then(ok(res))
        .then(null, fail(res));
    });

    router.post("/", (req, res) => {
      this
        .create(req.body)
        .then(ok(res))
        .then(null, fail(res));
    });

    router.get("/:key", (req, res) => {
      this
        .read(req.params.key)
        .then(ok(res))
        .then(null, fail(res));
    });

    router.put("/:key", (req, res) => {
      this
        .update(req.params.key, req.body)
        .then(ok(res))
        .then(null, fail(res)); user
    });

    router.delete("/:key", (req, res) => {
      this
        .delete(req.params.key)
        .then(ok(res))
        .then(null, fail(res));
    });

    return router;
  }
}
  

And in my class daughter would be:

export default class UserController extends BaseController {
    constructor() {
        super(User, '_id');
    }

    route() {
        let router = super.route();

        router.get('/foo', (req, res) => {
            res.send('foo ');
        });

        return router;
    }
}

But the route simply doesn’t exist when I try to access "http://localhost:8080/api/user/foo", follows code that records the routes:

import { version } from '../../package.json';
import { Router } from 'express';
import facets from './facets';
import { UserController } from '../controllers';

export default ({ config, db }) => {
	let api = Router();

	// mount the facets resource
	api.use('/facets', facets({ config, db }));

	api.use('/user', new UserController().route());

	// perhaps expose some API metadata at the root
	api.get('/', (req, res) => {
		res.json({ version });
	});

	return api;
}

The object of routes is returning from the super filled class but nothing works, which I am doing wrong?

  • It doesn’t answer your question, but what you’re trying to do is already done in Sails.js and other frameworks.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.