Created
November 16, 2015 23:13
-
-
Save narqo/635b4018834a5bc47f66 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://github.com/narqo/node-mcro