I am using node.js Restify v4.0.3. The REST API server supports HTTP and HTTPS. Currently, the code for declaring the servers violates the DRY (don't repeat yourself) principle.
Declaration code for HTTP server.
var server = restify.createServer({
name: 'myapp',
version: '1.0.0'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());
server.opts(/.*/, function (req,res,next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
res.send(200);
return next();
});
server.listen(8400, function () {
console.log('%s listening at %s', server.name, server.url);
});
Declaration code of HTTPS server
var https_options = {
name: 'myapp',
version: '1.0.0',
key: fs.readFileSync('./HTTPS.key'), //on current folder
certificate: fs.readFileSync('./HTTPS.cert'),
};
var https_server = restify.createServer(https_options);
https_server.use(restify.acceptParser(server.acceptable));
https_server.use(restify.queryParser());
https_server.use(restify.bodyParser());
https_server.use(restify.CORS());
https_server.opts(/.*/, function (req,res,next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", req.header("Access-Control-Request-Method"));
res.header("Access-Control-Allow-Headers", req.header("Access-Control-Request-Headers"));
res.send(200);
return next();
});
https_server.listen(8500, function () {
console.log('%s listening at %s', https_server.name, https_server.url);
});
There is quite a bit of repetition. How can the code be improved to conform to DRY principle?