Express: Using Decorators in Express

Created on 17 Oct 2016  路  5Comments  路  Source: expressjs/express

I wanted Decorators to be part of Express restful API system, where you can define the url, method etc using decorators. This exist in Java Spring Framework like

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

ref: https://spring.io/guides/gs/rest-service/

so in Express this

app.get('/greeting', function (req, res) {
  res.send('Hello World!');
});

could convert to

@RestController()
class GreetingController() {
    @Request('/greeting')
    greeting(req, res) {
       res.send('Hello World!');
    }
}

This way a lot of Java Developers would be interested in NodeJS and Express environment and MEAN 2 would be great because Angular 2 also uses decorators 馃槃

Most helpful comment

@mohammedzamakhan You could do it now, tho not with the syntax you've added here.

var router = express.Router();
function Request (method, path) {
  return function (fn) {
    router[method.toLowerCase()](path, fn);
  }
}

@Request('GET', '/greeting')
function greeting (req, res) {}

I'm not sure it's really up to express to add that support, it's more suited to a third party lib.

All 5 comments

Huh, I didn't even realize decorators have been added to JavaScript at all. What would Express need to do to support them, if it hypothetically wanted to?

They haven't been, it's still an experimental addition that only exists in babel.

Decorators is still in stage 2 which means that they are not yet a part of the language...

Ah, thanks guys :) So regardless of the merits of even handing decorators in Express, if it's not even a part of core JavaScript, I don't think now is the right time to support them.

FWIW, I did a quick Google and found https://www.npmjs.com/package/express-decorators which may do what you're looking for @mohammedzamakhan

@mohammedzamakhan You could do it now, tho not with the syntax you've added here.

var router = express.Router();
function Request (method, path) {
  return function (fn) {
    router[method.toLowerCase()](path, fn);
  }
}

@Request('GET', '/greeting')
function greeting (req, res) {}

I'm not sure it's really up to express to add that support, it's more suited to a third party lib.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

afanasy picture afanasy  路  3Comments

guyisra picture guyisra  路  3Comments

Domiii picture Domiii  路  3Comments

AndrewEQ picture AndrewEQ  路  4Comments

haider0324 picture haider0324  路  3Comments