项目作者: mauris

项目描述 :
Minimalistic JSON over TCP/TLS server framework (Express.js without the HTTP)
高级语言: JavaScript
项目地址: git://github.com/mauris/madtom.git
创建时间: 2019-05-05T09:43:17Z
项目社区:https://github.com/mauris/madtom

开源协议:

下载


Madtom JSON over TCP Framework

Inspired by the json-over-tcp project and Express.js Web Framework, Madtom is a TCP server framework that can process requests and responses in a middleware fashion similar to Express.js.

Optionally, Madtom also supports TCP with TLS out of the box.

  1. const madtom = require('madtom');
  2. const app = madtom({
  3. /* Enable server-side TLS identity */
  4. tls: {
  5. key: './server-key.pem',
  6. cert: './server-cert.pem',
  7. },
  8. });
  9. /* use JSON as the parser for request body */
  10. app.use(madtom.parsers.json);
  11. app.tryCatch((err, req, res, next) => {
  12. console.log(`Error occurred:\n\t${err.message}`);
  13. });
  14. /*
  15. Add a router to the
  16. */
  17. const router = madtom.Router();
  18. app.use(router);
  19. /*
  20. Executes only when request document has
  21. the key "fruit" in it.
  22. */
  23. router
  24. .filter(doc => doc.fruit)
  25. .execute((req, res, next) => {
  26. if (req.body.fruit === 'tomato') {
  27. // handle the error
  28. next(new Error('I think tomato is considered vegetable'));
  29. return;
  30. }
  31. res.json({ status: 'ok' });
  32. });
  33. /*
  34. Executes only when request document is an object
  35. and has the key "consume".
  36. emitKeyValue() will transform the request document into an
  37. array of key-value.
  38. */
  39. router
  40. .isObject()
  41. .hasKey('consume')
  42. .emitKeyValue()
  43. .execute((req, res, next) => {
  44. req.body.forEach((tuple) => {
  45. console.log(`${tuple.key}: ${tuple.value}`);
  46. });
  47. res.json({ status: 'ok' });
  48. });
  49. /*
  50. Start listening
  51. */
  52. app.listen(8001, 'madtom.test', () => {
  53. console.log('listening!');
  54. });

Source code open sourced under the MIT license.