Skip to content

Instantly share code, notes, and snippets.

@narqo
Created November 16, 2015 23:13
Show Gist options
  • Save narqo/635b4018834a5bc47f66 to your computer and use it in GitHub Desktop.
Save narqo/635b4018834a5bc47f66 to your computer and use it in GitHub Desktop.
import connect from 'connect';
class ErrEmpty extends Error {
constructor() {
super()
this.message = 'Empty string';
}
}
class StringService {
uppercase(s) {
if (typeof s !== 'string' || !s.length) {
throw new ErrEmpty();
}
return s.toUpperCase();
}
count(s) {
return s.length;
}
}
const toSvcArgs = (data) => { s: data.s };
const fromSvcResults = (err, val="") => { v: val, err };
const makeUppercaseEndpoint = svc => function(ctx, req) {
var params = toSvcArgs(req);
var svcRes, err = null;
try {
svcRes = svc.uppercase(params.s);
catch (err_) {
err = err_;
}
return fromSvcResults(err, svcRes);
};
const makeCountEndpoint = svc => function(ctx, req) {
var params = toSvcArgs(req);
var v = svc.count(params.s);
return fromSvcResults(null, v);
};
class Controller {
constructor(ctx, e, dec, enc, ...options) {
this.ctx = ctx;
this.endpoint = e;
this.decode = dec,
this.encode = enc;
// @todo: process options
}
handle(req_, res_) {
//var ctx = new Context(this.ctx);
var req = this.decode(req_);
// @todo Error handeling
var results = this.endpoint(ctx, req);
return this.encode(res_, results);
}
}
// app.js
const decodeReq = req => req.body;
const encodeRes = (res, data) => res.end(JSON.stringify(data));
const app = connect(function(req, res) {
var ctx = new Map();
const svc = new StringService();
const uppercaseCtrl = new Controller(
ctx,
makeUppercaseEndpoint(svc),
decodeReq,
encodeRes
);
const countCtrl = new Controller(
ctx,
makeCountEndpoint(srv),
decodeReq,
encodeRes
);
switch (req.url) {
case '/uppercase':
uppercaseCtrl.handle(req, res);
break;
case '/count':
countCtrl.handle(req, res);
break;
}
});
app.listen(3001, () => console.log('Server is here!'));
@narqo
Copy link
Author

narqo commented Jun 5, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment