@@ -12,12 +12,14 @@ const path = require('path');
1212
1313
1414// npm-installed modules
15+ const _ = require ( 'lodash' ) ;
1516const Debug = require ( 'debug' ) ;
1617const express = require ( 'express' ) ;
1718
1819
1920// own modules
2021const engine = require ( '../engine' ) ;
22+ const utils = require ( './utils' ) ;
2123
2224
2325// module variables
@@ -31,6 +33,13 @@ exports = module.exports = router;
3133exports . router = router ;
3234
3335
36+ // API doc
37+ router . get ( '/' , function ( req , res , next ) {
38+ const filepath = path . resolve ( __dirname , '../docs/api.md' ) ;
39+ return utils . renderMarkdownPage ( req , res , next , filepath ) ;
40+ } ) ;
41+
42+
3443// serving data for all networks
3544router . get ( '/networks' , function ( req , res , next ) {
3645 return res . json ( {
@@ -51,13 +60,49 @@ router.get('/networks/:network', function(req, res, next) {
5160} ) ;
5261
5362
63+ // calculations
64+ router . post ( '/cost' , function ( req , res , next ) {
65+ if ( ! _ . isString ( req . body . network )
66+ || ! _ . isNumber ( req . body . amount )
67+ || ! _ . isString ( req . body . transactionType )
68+ || ! _ . isString ( req . body . transactor ) ) {
69+ const error = new Error ( 'missing/invalid parameter' ) ;
70+ error . statusCode = 400 ;
71+ return next ( error ) ;
72+ }
73+
74+ let cost ;
75+ try {
76+ cost = engine . math . calculate ( req . body . network , req . body ) ;
77+ } catch ( ex ) {
78+ return next ( ex ) ;
79+ }
80+
81+ return res . json ( {
82+ cost,
83+ } ) ;
84+ } ) ;
85+
86+
87+ // API 404
88+ router . use ( function ( req , res , next ) {
89+ const error = new Error ( 'API Endpoint Not Found' ) ;
90+ error . statusCode = 404 ;
91+ return next ( error ) ;
92+ } ) ;
93+
94+
5495// API Error handler
55- router . use ( function ( err , req , res , next ) {
56- err . statusCode = err . statusCode || 500 ;
57- if ( err . statusCode == = 500 ) {
58- logger . error ( err ) ;
96+ router . use ( function ( error , req , res , next ) {
97+ error . statusCode = error . statusCode || 500 ;
98+ if ( error . statusCode > = 500 ) {
99+ logger . error ( error ) ;
59100 }
60- return res . status ( err . statusCode ) . json ( {
61- error : err ,
101+ return res . status ( error . statusCode ) . json ( {
102+ error : {
103+ message : error . message ,
104+ name : error . name ,
105+ statusCode : error . statusCode ,
106+ } ,
62107 } ) ;
63108} ) ;
0 commit comments