├── .gitignore ├── package.json ├── README.md ├── index.js ├── LICENSE ├── crud.js └── example.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # Logs 4 | logs 5 | *.log 6 | npm-debug.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # nyc test coverage 20 | .nyc_output 21 | 22 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 23 | .grunt 24 | 25 | # node-waf configuration 26 | .lock-wscript 27 | 28 | # Compiled binary addons (http://nodejs.org/api/addons.html) 29 | build/Release 30 | 31 | # Dependency directories 32 | node_modules 33 | jspm_packages 34 | 35 | # Optional npm cache directory 36 | .npm 37 | 38 | # Optional REPL history 39 | .node_repl_history 40 | 41 | .idea/ -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "js-api", 3 | "version": "1.5.0", 4 | "description": "JavaScript/JSON objects to REST API in seconds.", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node example.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/soygul/js-api.git" 12 | }, 13 | "author": "Teoman Soygul", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/soygul/js-api/issues" 17 | }, 18 | "homepage": "https://github.com/soygul/js-api", 19 | "dependencies": { 20 | "koa": "1.6.2", 21 | "koa-bodyparser": "2.5.0", 22 | "koa-cors": "0.0.16", 23 | "koa-logger": "1.3.1", 24 | "koa-route": "2.4.2", 25 | "lodash": "4.17.21", 26 | "request": "2.88.2" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # js-api 2 | Creates a REST API server from given JavaScript/JSON objects. 3 | Uses [Koa](https://github.com/koajs/koa) for the REST API. 4 | Extendable with custom routes and middleware. 5 | 6 | ## Quickstart 7 | Install the package in your project directory: 8 | 9 | ```bash 10 | npm install js-api 11 | ``` 12 | 13 | Start js-api server with some data: 14 | 15 | ```javascript 16 | var jsapi = require('js-api'); 17 | 18 | var data = {posts: [{id: 'p1', title: 'first post', body: 'lorem ipsum'}]}; 19 | 20 | jsapi.start(data, 3000); 21 | ``` 22 | 23 | Now browse to [http://localhost:3000/posts](http://localhost:3000/posts) and you will see the posts in JSON format. 24 | 25 | ## Custom Routes and Middleware 26 | See [example.js](example.js) for a complete example with custom middleware and custom route definitions for resources. 27 | 28 | You can download the entire repo and start the example directly with: 29 | 30 | ```bash 31 | npm install 32 | npm start 33 | ``` 34 | 35 | And browse to [http://localhost:3000/posts](http://localhost:3000/posts) to see the contents of the example. 36 | 37 | ## License 38 | MIT 39 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Entry point for JS-API app. 5 | * Initializes the database and starts listening for requests on configured port. 6 | */ 7 | 8 | var koa = require('koa'), 9 | app = koa(), 10 | logger = require('koa-logger'), 11 | cors = require('koa-cors'), 12 | bodyParser = require('koa-bodyparser'), 13 | _ = require('lodash'), 14 | crud = require('./crud'); 15 | 16 | // Koa config 17 | app.use(logger()); 18 | 19 | app.use(cors({ 20 | maxAge: 0, 21 | credentials: true, 22 | methods: 'GET, HEAD, OPTIONS, PUT, POST, DELETE', 23 | headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization' 24 | })); 25 | 26 | app.use(bodyParser()); 27 | 28 | app.start = function (data, port) { 29 | port = port || 3000; 30 | data = data || {}; 31 | 32 | // mount all resources defined in data as a generic crud route 33 | _.forOwn(data, function(resource, key) { 34 | crud.init(app, resource, resource.route || key); 35 | }); 36 | 37 | app.listen(port) 38 | 39 | console.log('JS-API server started on port %s', port) 40 | } 41 | 42 | module.exports = app; 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Teoman Soygul 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /crud.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Generates generic Koa CRUD controller for a given resource. 5 | */ 6 | 7 | var route = require('koa-route'), 8 | _ = require('lodash'); 9 | 10 | /** 11 | * Register Koa routes on a given Koa app for a given resource. 12 | */ 13 | exports.init = function (app, resource, routeName) { 14 | routeName = '/' + routeName 15 | 16 | // handle non-array objects 17 | if (!Array.isArray(resource)) { 18 | app.use(route.get(routeName, function *() { 19 | this.body = resource 20 | })); 21 | 22 | return; 23 | } 24 | 25 | // list all items filtered by query (if any) 26 | app.use(route.get(routeName, function *() { 27 | this.body = _.filter(resource, this.query) 28 | })); 29 | 30 | // get one item by id 31 | app.use(route.get(routeName + '/:id', function *(id) { 32 | var item = _.find(resource, {id: id}); 33 | if (!item) { 34 | this.status = 404; 35 | return; 36 | } 37 | this.body = item; 38 | })); 39 | 40 | // create new item 41 | app.use(route.post(routeName, function *() { 42 | resource.push(this.request.body); 43 | this.status = 201; 44 | this.body = this.request.body; 45 | })); 46 | 47 | // update item by id 48 | app.use(route.put(routeName + '/:id', function *(id) { 49 | var i = _.findIndex(resource, {id: id}); 50 | resource[i] = this.request.body; 51 | this.status = 200; 52 | this.body = this.request.body; 53 | })); 54 | 55 | // delete item by id 56 | app.use(route.delete(routeName + '/:id', function *(id) { 57 | var i = _.findIndex(resource, {id: id}); 58 | resource.splice(i, 1); 59 | this.status = 204; 60 | })); 61 | }; 62 | -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | var jsapi = require('./index'); // this is a regular Koa app 2 | 3 | var data = { 4 | posts: [ 5 | {id: 'p1', title: 'first post', body: 'lorem ip sum'}, 6 | {id: 'p2', title: 'second post', body: 'dolor sit amet'} 7 | ], 8 | users: [ 9 | {id: 'u1', name: 'Chuck'} 10 | ], 11 | home: { 12 | title: 'My Title', 13 | content: 'Lorem ipsum.' 14 | } 15 | }; 16 | 17 | // define custom API route for 'users' 18 | data.users.route = 'local-users' 19 | 20 | // define custom Koa middleware/routes if necessary 21 | jsapi.use(function *(next){ 22 | var start = new Date; 23 | yield next; 24 | var ms = new Date - start; 25 | console.log('%s %s - %s', this.method, this.url, ms); 26 | }); 27 | 28 | jsapi.start(data, 3000); 29 | 30 | // ########### Below is the testing part for the above server definition ############ // 31 | 32 | console.log('Running example tests:') 33 | 34 | var request = require('request'); 35 | var uri = 'http://localhost:3000/' 36 | 37 | request({url: uri + 'local-users/u1', json: true}, function (error, response, body) { 38 | console.log('get user #1:', body) 39 | }) 40 | 41 | request({url: uri + 'posts/p1', json: true}, function (error, response, body) { 42 | console.log('get post #1:', body) 43 | }) 44 | 45 | request({url: uri + 'posts', method: 'POST', json: {id:'p3', title: 'third post', body: 'quick brown fox'}}, function (error, response, body) { 46 | console.log('create post #3:', body) 47 | }) 48 | 49 | request({url: uri + 'posts/p1', method: 'PUT', json: {id:'p1', title: 'first post', body: 'some proper body'}}, function (error, response, body) { 50 | console.log('update post #1:', body) 51 | }) 52 | 53 | request({url: uri + 'posts', json: true}, function (error, response, body) { 54 | console.log('all posts:', body) 55 | }) 56 | 57 | request({url: uri + 'home', json: true}, function (error, response, body) { 58 | console.log('home page:', body) 59 | }) --------------------------------------------------------------------------------