{"id":15502730,"url":"https://github.com/j-siu/simple-api-express","last_synced_at":"2025-03-28T18:23:02.808Z","repository":{"id":57359790,"uuid":"68978058","full_name":"J-Siu/simple-api-express","owner":"J-Siu","description":"simple-api-express is an expressjs api handler that work with simple-api-client-ng2 or simple-api-client-node","archived":false,"fork":false,"pushed_at":"2022-05-19T00:20:01.000Z","size":17,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-23T00:32:17.226Z","etag":null,"topics":["api","api-handler","api-server","expressjs-api-handler","node","node-module","nodejs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/J-Siu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-09-23T01:47:00.000Z","updated_at":"2022-05-16T06:12:20.000Z","dependencies_parsed_at":"2022-09-06T21:41:18.631Z","dependency_job_id":null,"html_url":"https://github.com/J-Siu/simple-api-express","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/J-Siu%2Fsimple-api-express","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/J-Siu%2Fsimple-api-express/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/J-Siu%2Fsimple-api-express/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/J-Siu%2Fsimple-api-express/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/J-Siu","download_url":"https://codeload.github.com/J-Siu/simple-api-express/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246077376,"owners_count":20719978,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-handler","api-server","expressjs-api-handler","node","node-module","nodejs"],"created_at":"2024-10-02T09:10:53.174Z","updated_at":"2025-03-28T18:23:02.779Z","avatar_url":"https://github.com/J-Siu.png","language":"TypeScript","readme":"# Angular Simple API Express [![Paypal donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/donate/?business=HZF49NM9D35SJ\u0026no_recurring=0\u0026currency_code=CAD)\n\n[simple-api-express](https://github.com/J-Siu/simple-api-express) is an ExpressJS api handler (NOT middleware) that work with [simple-api-client-ng2](https://github.com/J-Siu/ng2-simple-api-lib), an Angular api service.\n\n### Table Of Content\n\u003c!-- TOC --\u003e\n\n- [Install](#install)\n- [Usage Flow](#usage-flow)\n- [API](#api)\n  - [constructor](#constructor)\n  - [debug](#debug)\n  - [list](#list)\n  - [register](#register)\n  - [registerObject](#registerobject)\n  - [response](#response)\n  - [handler](#handler)\n- [Error Handling](#error-handling)\n  - [Not Found](#not-found)\n  - [Callback throw](#callback-throw)\n- [Example](#example)\n- [Repository](#repository)\n- [Contributors](#contributors)\n- [Changelog](#changelog)\n- [License](#license)\n\n\u003c!-- /TOC --\u003e\n\u003c!--more--\u003e\n\n### Install\n\n```sh\nnpm install simple-api-express\n```\n\n### Usage Flow\n\n`simple-api-express` depends on ExpressJS middleware bodyParser for json body decode.\n\n```javascript\nconst express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\napp.use(bodyParser.json());\napp.listen(8080);\n```\n\nImport `simple-api-express`:\n\n```js\nconst SimpleApi = require('simple-api-express').SimpleApi;\n```\n\nCreate api object with base url:\n\n```js\nconst apiDemoUrl = '/demo';\nvar apiDemo = new SimpleApi(apiDemoUrl, true); // enable debug\n```\n\nRegister a function as api callback:\n\n```js\napiDemo.register('echo2',param =\u003e 'echo2:' + param);\n```\n\nYou can also register all functions of an object as api callbacks:\n\n```js\napiDemo.registerObject(require('./api-object').DemoObj);\n```\n\nUse express post and `SimpleApi.response()` to handle incoming api request:\n\n```js\n// Post request + API response\napp.post(path.join(apiDemoUrl, '*'), (req, res) =\u003e apiDemo.response(req, res))\n```\n\n`SimpleApi.handler()` can be use if additional action(eg: customizing response header or error page) is required before reply:\n\n```js\n// Post request + API handler\napp.post(path.join(apiDemoUrl, '*'), (req, res) =\u003e {\n  // Log request body before process\n  console.log(req.body);\n  try {\n    // Manual handler used, server code responsible to send result and handle error\n    // Use manual handler if custom header or custom 404 error are needed\n    let result = apiDemo.handler(req);\n\n    // Result must be return in json format\n    res.json(result);\n  }\n  catch (e) {\n    // Catch api not found error\n    res.status(e.status).end(e.error);\n  }\n})\n```\n\n### API\n\n#### constructor\n\n`SimpleApi(baseUrl:string, debug:boolean)`\n\n- `baseUrl` will prefix all api url registered to this SimpleApi instance.\n- `debug` will enable/disable debug log. Default to false.\n\n```js\nconst SimpleApi = require('simple-api-express').SimpleApi;\nconst apiDemoUrl = '/demo';\nvar apiDemo = new SimpleApi(apiDemoUrl, true); // enable debug\n```\n\n#### debug\n\n`debug(enable: boolean)` can enable/disable debug log.\n\n```js\napiDemo.debug(false);\n```\n\n#### list\n\n`list()` return a `string[]` containing all registered api url.\n\n```js\nconsole.log(apiDemo.list());\n```\n\nOutput:\n\n```js\n[ '/demo/echo', '/demo/echo2' ]\n```\n\n#### register\n\n`register(url:string,callback)` register a callback function to `url`\n\n- `url` : Api url path after baseUrl. The resulting url for the api is baseUrl/url.\n- `callback` : a function that take a single argument as api parameter, and return a result.\n\n```js\napiDemo.register('echo2',param =\u003e 'echo2:' + param);\n```\n\n#### registerObject\n\n`registerObject(object)` register all functions of an object as api callbacks.\n\nAll functions of the object should take a single argument as api parameter, and return a result.\n\nThe function name will be used api url.\n\n```js\nvar DemoObj = {\n  echo(r) {\n    return r;\n  }\n}\n\napiDemo.registerObject(DemoObj);\n```\n\n#### response\n\n`SimpleApi.response(req, res)` is a handle function for incoming api post request. Api parameter will be passed to corresponding callback. Callback result will be passed back to api client.\n\n`req, res` are request and response object pass in from ExpressJs post.\n\n```js\n// Post request + API response\napp.post(path.join(apiDemoUrl, '*'), (req, res) =\u003e apiDemo.response(req, res))\n```\n\n#### handler\n\n`SimpleApi.handler(req)` is an api handler function. It will invoke the corresponding callback base on the request url, and return the result.\n\nIT WILL NOT send out the result.\n\nIT IS NOT a ExpressJs post handler function. It needed to be called INSIDE the post handler function.\n\nApi handler can be use if additional action(eg: customizing response header or error page) is required:\n\n```js\n// Post request + API handler\napp.post(path.join(apiDemoUrl, '*'), (req, res) =\u003e {\n  // Log request body before process\n  console.log(req.body);\n  try {\n    // Manual handler used, server code responsible to send result and handle error\n    // Use manual handler if custom header or custom 404 error are needed\n    let result = apiDemo.handler(req);\n\n    // Result must be return in json format\n    res.json(result);\n  }\n  catch (e) {\n    // Catch api not found error\n    res.status(e.status).end(e.error);\n  }\n})\n```\n\n### Error Handling\n\nThere are two types of error.\n\n#### 404 Not Found\n\nWhen `response()` is called with an non-exist api url, it will response with a HTTP 404 Not Found.\n\nWhen `handle()` is called with an non-exist api url, it will throw an error, which can be caught in the post handle function.\n\n#### Callback throw\n\nWhen `response()` is called, and the invoked api callback throw an error, which will be passed to remote client.\n\nThe remote client, using [simple-api-client-ng2](https://github.com/J-Siu/ng2-simple-api-lib), will throw an exception with the error.\n\nWhen `handle()` is called, and the invoked api callback throw an error, the error can be inspected from the result object.\n\n```js\nlet result = apiDemo.handler(req);\n\n// If api callback return\nif(result.error) {\n  console.log(result.error);\n}\n\n// Result must be return in json format\nres.json(result);\n```\n\nThe remote client, using [simple-api-client-ng2](https://github.com/J-Siu/ng2-simple-api-lib), will throw an exception with the error.\n\n### Example\n\nA detail example for how [simple-api-express](https://github.com/J-Siu/simple-api-express) and [simple-api-client-ng2](https://github.com/J-Siu/ng2-simple-api-lib) work is in:\n\n- [ng2-simple-api-lib](https://github.com/J-Siu/ng2-simple-api-lib)\n\n### Repository\n\n- [simple-api-express](https://github.com/J-Siu/simple-api-express)\n\n### Contributors\n\n- [John Sing Dao Siu](https://github.com/J-Siu)\n\n### Changelog\n\n- 1.2.0\n  - Publish to NPM.\n- 1.2.1\n  - Fix Readme.md typo\n- 1.2.2\n  - Update package.json\n  - Update Readme.md\n- 4.0.0\n  - Match ExpressJS major version\n  - README.md clean up\n  - package.json clean up\n  - simple-api.ts uses typescript import\n- 5.0.0\n  - Move target from ES5 to ES2015\n\n### License\n\nThe MIT License\n\nCopyright (c) 2021\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","funding_links":["https://www.paypal.com/donate/?business=HZF49NM9D35SJ\u0026no_recurring=0\u0026currency_code=CAD"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fj-siu%2Fsimple-api-express","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fj-siu%2Fsimple-api-express","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fj-siu%2Fsimple-api-express/lists"}