pax_global_header00006660000000000000000000000064151615421150014513gustar00rootroot0000000000000052 comment=c329faa008676b6e310253648c6378533078baa7 pixl-server-api-1.0.9/000077500000000000000000000000001516154211500145515ustar00rootroot00000000000000pixl-server-api-1.0.9/.npmignore000066400000000000000000000000311516154211500165420ustar00rootroot00000000000000.gitignore node_modules/ pixl-server-api-1.0.9/README.md000066400000000000000000000147651516154211500160450ustar00rootroot00000000000000# Overview This module is a component for use in [pixl-server](https://www.github.com/jhuckaby/pixl-server). It implements a simple JSON REST API framework, and is built atop the [pixl-server-web](https://www.github.com/jhuckaby/pixl-server-web) component. You can use this to define your own API methods or API classes, which are invoked based on a URL pattern such as `/api/NAME` or `/api/CLASS/NAME`. The base URI is configurable. # Usage Use [npm](https://www.npmjs.com/) to install the module: ```sh npm install pixl-server pixl-server-web pixl-server-api ``` Here is a simple usage example. Note that the component's official name is `API`, so that is what you should use for the configuration key, and for gaining access to the component via your server object. ```js const PixlServer = require('pixl-server'); let server = new PixlServer({ __name: 'MyServer', __version: "1.0", config: { "log_dir": "/let/log", "debug_level": 9, "WebServer": { "http_port": 80, "http_htdocs_dir": "/let/www/html" }, "API": { "base_uri": "/api" } }, components: [ require('pixl-server-web'), require('pixl-server-api') ] }); server.startup( function() { // server startup complete server.API.addHandler( 'add_user', function(args, callback) { // custom request handler for our API callback({ code: 0, description: "Success!" }); } ); } ); ``` Notice how we are loading the [pixl-server](https://www.github.com/jhuckaby/pixl-server) parent module, and then specifying [pixl-server-web](https://www.github.com/jhuckaby/pixl-server-web) and [pixl-server-api](https://www.github.com/jhuckaby/pixl-server-api) as components: ```js components: [ require('pixl-server-web'), require('pixl-server-api') ] ``` This example demonstrates a very simple API service, which will answer to `/api/add_user` URIs, and sends back a serialized JSON response. # Configuration The configuration for this component is set by passing in a `API` key in the `config` element when constructing the `PixlServer` object, or, if a JSON configuration file is used, a `API` object at the outermost level of the file structure. It can contain the following keys: ## base_uri The `base_uri` property specifies the URL prefix that will activate the API service. Basically, this means the API service will "listen" for incoming web server requests that begin with this URL. The default value is `/api`, so API handlers are activated by `/api/HANDLER_NAME`. # Adding API Handlers To add an API handler, call the `addHandler()` method on the API component. You can access the API component by the `API` property in the main server object. Example: ```js server.API.addHandler( 'add_user', function(args, callback) { // custom request handler for our API callback({ code: 0, description: "Success!" }); } ); ``` Your handler method is passed an `args` object containing information about the request. See the [args](https://www.github.com/jhuckaby/pixl-server-web#args) documentation for details. The second argument to your handler function is a callback. After your API method is complete, invoke the `callback` function. Pass it an object, which will be serialized to JSON and sent back to the client. It is up to you how to handle errors, but the standard way is to include a `code` property, set to `0` for success, and any other value for error. Pass the error message in a `description` property, which can be omitted on success. The data passed to the callback function is sent directly to the web server, which actually accepts several formats. See [Sending Responses](https://www.github.com/jhuckaby/pixl-server-web#sending-responses) for details on how to send custom HTTP responses. # Adding API Namespaces You can actually add an entire class as an API "namespace". This means, incoming URLs will be matched against the namespace, and then a method name in the provided class. To do this, call the `addNamespace()` method on the API component, and pass in a namespace string, a function name prefix, and an object on which to invoke methods. Example: ```js server.API.addNamespace( "user", "api_", obj ); ``` This declares a namespace for `user`. So then, a URL such as `/api/user/add` would call the `api_add()` method on the provided `obj`. Another way to use this is to develop your own server component, and pass the component itself as the namespace object. For example, this implements an API into the [pixl-server-storage](https://www.github.com/jhuckaby/pixl-server-storage) component for putting and getting keys: ```js const Component = require("pixl-server/component"); module.exports = class MyStorageAPI extends Component { startup(callback) { this.storage = this.server.Storage; this.server.API.addNamespace( "storage", "api_", this ); callback(); } api_set(args, callback) { // set key in storage this.storage.put( args.query.key, args.query, function(err) { if (err) callback({ code: 1, description: err.message }); else callback({ code: 0 }); } ); } api_get(args, callback) { // get key from storage this.storage.get( args.query.key, function(err, data) { if (err) callback({ code: 1, description: err.message }); else callback({ code: 0, data: data }); } ); } }; ``` See the [Component Development](https://www.github.com/jhuckaby/pixl-server#component-development) section in the [pixl-server](https://www.github.com/jhuckaby/pixl-server) docs for more details on developing server components. # License **The MIT License (MIT)** Copyright (c) 2015 - 2016 Joseph Huckaby. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. pixl-server-api-1.0.9/api.js000066400000000000000000000110651516154211500156630ustar00rootroot00000000000000// Simple JSON API Server Component // A component for the pixl-server daemon framework. // Copyright (c) 2015 Joseph Huckaby // Released under the MIT License var Class = require("pixl-class"); var Component = require("pixl-server/component"); var Tools = require("pixl-tools"); module.exports = Class.create({ __name: 'API', __parent: Component, defaultConfig: { base_uri: '/api' }, handlers: null, namespaces: null, normalizeAPIName: function(name) { // normalize API name, lower-case alphanumeric + slashes + dashes + dots only return name.toString().toLowerCase().replace(/[^\w\/\-\.]+/g, ''); }, addHandler: function(name, callback) { // add handler method for root-level API, e.g. /api/add_user name = this.normalizeAPIName(name); this.logDebug(3, "Adding API handler for: " + name); this.handlers[name] = callback; }, addNamespace: function(name, prefix, obj) { // add namespace (API class), e.g. /api/user/add name = this.normalizeAPIName(name); this.logDebug(3, "Adding API namespace: " + name); this.namespaces[name] = { regexp: new RegExp( Tools.escapeRegExp(this.config.get('base_uri') + "/" + name + "/" ) + "(\\w+)" ), prefix: prefix || "", obj: obj }; }, startup: function(callback) { // start api service this.logDebug(3, "API service listening for base URI: " + this.config.get('base_uri') ); this.handlers = {}; this.namespaces = {}; // add web server handler for API requests var regex = new RegExp( Tools.escapeRegExp(this.config.get('base_uri')) + "/(\\w+)" ); this.server.WebServer.addURIHandler( regex, "API", this.handler.bind(this) ); // save regex for later (internal invoke) this.uri_regex = regex; callback(); }, handler: function(args, callback) { // handle API request, delegate to class or method var self = this; var uri = args.request.url.replace(/\?.*$/, ''); var name = args.matches[1]; // /api/add_user name = this.normalizeAPIName(name); // make sure params is an object if (!Tools.isaHash(args.params)) args.params = {}; this.emit('request', args, callback); // wrap callback so we can emit a response event var finish = this.listenerCount('response') ? function(...resArgs) { self.emit('response', args, resArgs); callback.apply( null, resArgs ); } : callback; this.logDebug(6, "Handling API request: " + args.request.method + ' ' + args.request.url, args.query); if (this.server.debug) { // only log details in server debug mode (security) this.logDebug(9, "API request details", { method: args.request.method, uri: args.request.url, params: args.params, files: args.files, cookies: args.cookies, headers: args.request.headers, ips: args.ips } ); } // Check root-level API handlers first if (this.handlers[name]) { this.logDebug(9, "Activating API handler: " + name + " for URI: " + uri); this.handlers[name]( args, finish ); } else if (this.namespaces[name]) { // We have a class handling this namespace var ns = this.namespaces[name]; var matches = uri.match(ns.regexp); if (matches) { // Well-formed namespaced URI, e.g. /api/user/add var subname = ns.prefix + matches[1]; if (subname in ns.obj) { // Namespace class supports the API call this.logDebug(9, "Activating namespaced API handler: " + name + "/" + subname + " for URI: " + uri); ns.obj[subname]( args, finish ); } else { var err_msg = "Unsupported API: " + name + "/" + subname; this.logError('api', err_msg); finish({ code: 1, description: err_msg }); } } else { var err_msg = "Invalid API URL: " + uri; this.logError('api', err_msg); finish({ code: 1, description: err_msg }); } } else { // Not found var err_msg = "Unsupported API: " + name; this.logError('api', err_msg); finish({ code: 1, description: err_msg }); } }, invoke: function(uri, params, callback) { // invoke a JSON API internally, and capture the response var args = { request: { method: "INTERNAL", url: uri, headers: { 'host': 'Internal', 'user-agent': 'Internal' } }, response: {}, query: Tools.parseQueryString(uri), matches: uri.match( this.uri_regex ), params: params, files: {}, cookies: {}, ip: '0.0.0.0', ips: ['0.0.0.0'], server: this.server }; if (!args.matches) { return callback({ code: 1, description: "Invalid API URL: " + uri }); } this.handler( args, callback ); }, shutdown: function(callback) { // shutdown api service callback(); } }); pixl-server-api-1.0.9/package.json000066400000000000000000000011401516154211500170330ustar00rootroot00000000000000{ "name": "pixl-server-api", "version": "1.0.9", "description": "A JSON REST API component for the pixl-server framework.", "author": "Joseph Huckaby ", "homepage": "https://github.com/jhuckaby/pixl-server-api", "license": "MIT", "main": "api.js", "repository": { "type": "git", "url": "https://github.com/jhuckaby/pixl-server-api" }, "bugs": { "url": "https://github.com/jhuckaby/pixl-server-api/issues" }, "keywords": [ "api", "json" ], "dependencies": { "pixl-server": "^1.0.0", "pixl-class": "^1.0.3", "pixl-tools": "^2.0.2" }, "devDependencies": {} }