APX (pronounced 'apex') is a non-opinionated, pluggable, modern API server designed to serve multiple communication mediums. The core APX plugins rely on popular community packages such as express, kue, socket.io, winston, object-manage to make configuration and two-way communication a breeze.
APX is built to be test friendly out of the box and comes with a testing
mode in the configuration that will use mock services and increase testing speed.
Well we have evaluated and contributed to several other API servers and just kept running into deficiencies, such as failure to use a popular library and not light-weight enough.
Thus, we created APX. It's light-weight, uses lots of modern packages, and wires them all together in an extensible stateful environment.
APX can be used homogeneously or through our generator.
$ npm install apx apx-express-socket.io --save
app.js
var apx = require('apx')
apx.once('ready',function(){
console.log('APX is ready!')
})
//pass options and configure
apx.start({
cwd: __dirname,
translators: ['apx-express-socket.io'],
express: {
routes: [
{get: {path: '/foo', file: 'actions/foo.js'}}
]
},
'socket-io': {
enabled: false
}
})
actions/foo.js
exports.name = 'foo'
exports.description = 'Example Foo Action'
exports.run = function(apx,req,res,next){
res.set('status','alive')
next()
}
Run the application
$ node app
Check the result of the action http://localhost:3000/foo
Our generator is a yeoman generator instance that will scaffold your entire API server.
NOTICE As of 0.6.0 the generator has not been completed yet. We are waiting for the API to solidify before creating the generator. This notice will be removed when the generator has been completed.
//install the generator
$ npm install generator-apx
//scaffold the initial app
$ yo apx
//scaffold a new action (with test)
$ yo apx:action <name>
//scaffold a new helper (with test)
$ yo apx:helper <name>
//scaffold a new initializer
$ yo apx:initializer <name>
//scaffold a new model
$ yo apx:model <name>
//scaffold a new service (with test)
$ yo apx:service <name>
//scaffold a new test (with test)
$ yo apx:task <name>
//scaffold a new translator
$ yo apx:translator <name>
APX consists of several well-known idioms
Actions are the bread and butter of an API server they serve all requests and build responses. Actions are also in charge of firing non-periodic tasks and utilizing services.
Helpers do not get loaded by the APX loading service however helpers
are meant to be common modules that assist actions and tasks. Generally
these are libraries that augment the req
,res
variables.
Initializers get executed when the server starts up and are only executed once. These are useful for setting up database connections and loading additional items into the environment.
Middleware is inspired by the idea of Connect Middleware and uses the same principle format.
Middleware is executed before actions are fired and is passed the Request and Response objects for augmentation.
Middleware is also the prescribed location to setup authentication handlers.
Models are optional, but since using models to store data has become so common it seems silly not to support them in context and generators. Models do not get loaded by the APX framework, but can be added during an initializer or per action or task.
Services are just libraries that are treated as singletons. Services should be used to maintain in-memory information, and/or provide access to data providers. Models are services but services are not necessarily models.
Tasks are jobs which are run either periodically or scheduled to run by an action. Tasks are considered headless and while they consume request data. They do not provide response data. They can, however, log using winston.
In other frameworks these are sometimes called "servers". Translators are the
middleware that consumes connections and produce generic Request
and Response
objects. An example of a translator would be an express HTTP server.
All parts of the structure are implemented in plugins. APX follows a simple plugin format that is similar in all parts of user space. The main APX package only provides the plugin loader and depends on plugins to add functionality to the system. This allows APX to be non-opinionated.
There are a couple common verbs used in plugins.
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of task' //verbose description for generating maps
exports.run = function(apx,req,res,next){} //code to be executed by apx and fire the next(err) at the end
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of model' //verbose description for generating maps
exports.helper = {} //object exported by the helper can also be a constructor
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of initializer' //verbose description for generating maps
exports.start = function(apx,next){} //code to be executed to start the initializer, firing next(err) at the end
exports.stop = function(apx,next){} //code to be executed to stop the initializer, firing next(err) at the end
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of middleware' //verbose description for generating maps
//pre only
exports.run = function(apx,req,res,next){} //constructor function with a prototype for instantiation (for pre run only)
//-- or --
//pre and post
exports.pre = function(apx,req,res,next){} //run this function before the action
exports.post = function(apx,req,res,next){} //runt this function after the action
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of model' //verbose description for generating maps
exports.schema = {} //schema used to create the model
exports.model = {} //model object created by desired database software
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of service' //verbose description for generating maps
exports.service = function(){} //constructor function with a prototype for instantiation
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of action or task' //verbose description for generating maps
exports.start = function(apx,next){} //code to be executed to start the translator, firing next(err) at the end
exports.stop = function(apx,next){} //code to be executed to stop the translator, firing next(err) at the end
exports.name = 'name' //should be concise and match the file name
exports.description = 'description of task' //verbose description for generating maps
exports.run = function(apx,req,next){} //code to be executed by apx and fire the next(err) at the end
Clustering in APX is a breeze. Simply use cluster-master
Here is a quick example
app.js
var apx = require('./apx')
apx.once('ready',function(apx){
console.log('APX is ready!',apx)
})
apx.start({
cwd: __dirname + '/app',
config: ['config.json'],
initializers: ['apx-kue'],
tasks: ['tasks/*.js'],
translators: ['apx-express-socket.io']
express: {
port: 3000
}
})
server.js
var clusterMaster = require('cluster-master')
clusterMaster({
exec: 'app.js',
env: {NODE_ENV: 'production'},
repl: {address: '127.0.0.1', port: 3002}
})
To start the cluster simply run
$ node server
APX is an EventEmitter and will emit various actions during its lifecycle that can be used to hook for additional functionality.
NOTE The event emitter for APX is a singleton so be careful when
registering events as they may get fired by more than one instance. Thus,
its important to use the once
operator on a lot of one-off events. Then
use the dead
event to re-arm.
Fired each time the readyState of the system changes.
var apx = require('apx')
apx.on('readyStateChange',function(readyState){
console.log('APX changed ready state to ' + readyState)
})
The following ready states are supported.
Fired any time an error occurs.
var apx = require('apx')
apx.on('error',function(err){
console.log('APX had an error',err)
})
Fired when configuration and init is completed
var apx = require('apx')
apx.on('ready',function(inst){
console.log('APX is ready',instance)
})
The instance after init is passed to the event.
Fired after shutdown has been completed.
var apx = require('apx')
apx.on('dead',function(inst){
console.log('APX has died',instance)
})
The instance after shutdown is passed to the event.
Fired before running an action.
var apx = require('apx')
apx.on('runActionBefore',function(action){
console.log('APX action before',action)
})
The action object is passed to the event.
Fired after running an action.
var apx = require('apx')
apx.on('runActionAfter',function(action){
console.log('APX action after',action)
})
The action object is passed to the event.
Fired before running a task.
var apx = require('apx')
apx.on('runTaskBefore',function(task){
console.log('APX task before',task)
})
The task object is passed to the event.
Fired after running a task.
var apx = require('apx')
apx.on('runTaskAfter',function(task){
console.log('APX task after',task)
})
The task object is passed to the event.
NOTE the instance is destroyed after this event.
APX uses object-manage to load and manage configuration data.
This also means the APX instance emits the events from object-manage see below.
testing
false
Testing mode will use fakeredis as much as possible and will not start listening on any ports. However it will still offer a full featured environment for writing tests. Testing mode will also not start Kue which should not be needed to test tasks.
cwd
''
The current working directory is used when loading actions, services, and tasks.
initializers
[]
An array of globs or objects or absolute file paths. That should be executed when the server is started.
tasks
[]
An array of globs or objects or absolute file paths. That will resolve to tasks.
This must be provided at config time to they can be loaded into Kue and scheduled if needed.
translators
[]
An array of globs or objects or absolute file paths. That will resolve to translators that should be started when the server is started
The lifecycle functions control how APX is started, stopped and configured.
Pass configuration parameters and instantiate the library. Does not start initializers or translators.
apx.setup({
cwd: __dirname
})
Starts the APX server by starting initializers and translators. Once that is compelte
it fires the ready
event which is passed the instance of APX.
apx.setup({
cwd: __dirname
})
apx.start()
//or for more convenience
apx.start({
cwd: __dirname
})
Note If no object is passed to start and setup has not been called APX will
throw an exception Tried to start APX without setting it up
Stops the APX server by stopping initializers and translators. Once that is complete
it fires the dead
event and destroys the instance.
apx.once('dead',function(){
console.log('APX is now dead')
})
apx.once('ready',function(){
apx.stop()
})
apx.start({cwd: __dirname})
Restart the APX server by stopping initializers and translators and then restarting them.
Stop will fire the dead
event.
Start will fire the ready
event.
apx.on('dead',function(){
console.log('APX is now dead')
})
apx.on('ready',function(){
console.log('APX is now ready')
})
apx.once('ready',function(){
apx.restart()
})
apx.start({cwd: __dirname})
Reference to the Apx constructor and its prototype. Useful for overriding prototypes before startup.
console.log(apx.Apx.prototype.readyState) //0
The current instance of APX is stored here. This can be use for mocking testing and passing the instance instead of having APX do it manually.
var initializer = require('apx-mongoose')
initializer.start(apx.instance,function(){
console.log('Manually started apx-mongoose')
})
Note the instance will be null
by default when APX has either yet to be started or after being stopped.
In APX the request and response objects create the common layer that translators iterate. They are instances of object-manage and expose all the available methods. These objects, however, are not streams. This is a limitation in some cases but it is the only to make the call stack for middleware usable.
Nearly all API servers implement commands and it is up to the translator to supply any uploaded files which should be written to temporary files using a tool like formidable. After that the action can direct the file to the correct location or transfer it to a storage cluster.
The request and response objects support a file object that points to an incoming temporary file or a file that should be streamed to a file.
If there is a situation where file support is more important than command support then raw stream iteration should be implemented in the translator. It is easy to take existing translators and modify them in userspace.
The request object contains information that is passed along from the request paths from the translator and is supplied
in object notation. Thus, req.get('propertyName')
is the most common usage to retrieve information. However to allow
for the receiving of files there is a req.files
array that shall be populated with files that were written to
temporary files during the request.
In order to access parts of the translator for more control over specific access mediums like the HTTP server the raw
request object shall be provided via req.raw
Example
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
req.get('foo') //bar
req.raw.query.foo //bar
res.success()
next()
}
As a convenience for translators to add files to the request object the addFile()
method exists.
Example
var req = new Request()
req.addFile('foo.txt')
req.addFile('bar.txt')
The response object is built by the action and middleware which is then passed on to the user through the translators desired output format. In most cases the output format is JSON but this is sometimes configurable at the translator level.
To allow the sending of raw data rather than JSON or any other format that can be transformed from an object the add()
method comes in handy.
Example
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
res.add('content to show')
res.add('more content to show')
next()
}
As a convenience method success()
exists to signal success to the client. This method uses a standard response format.
That resembles the following. Success also accepts a few argument combinations to allow more structured responses
without additional function calls.
Format
{"status": "ok", "message": "success", "code": "0"}
Example
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
res.success() //sends message: 'success', code: '0'
res.success('foo') //sends message: 'foo', code: '0'
res.success('foo',4) //send message: 'foo', code: '4'
res.success('foo',4,{id: 'bar'}) //sends message: 'foo', code: '4', id: 'bar'
res.success('foo',{id: 'bar'}) //sends message: 'foo', code: '0', id: 'bar'
res.success({id: 'bar'}) //sends message: 'success', code: '0', id: 'bar'
next()
}
For easier error handling the error method can be used to pass an erroneous response to the client and accepts a few different combinations of arguments to supply the user with information about the error.
Format
{"status": "error", "message": "error", "code": "1"}
Example
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
res.error() //sends message: 'An error has occurred', code: '1'
res.error('foo') //sends message: 'foo', code: '1'
res.error('foo',4) //send message: 'foo', code: '4'
res.error('foo',4,{id: 'bar'}) //sends message: 'foo', code: '4', id: 'bar'
res.error('foo',{id: 'bar'}) //sends message: 'foo', code: '1', id: 'bar'
res.error({id: 'bar'}) //sends message: 'An error has occurred', code: '1', id: 'bar'
next()
}
Sometimes it is useful to send clients a file thus the sendFile(path)
method exists. This will notify the translator
that a file should be sent to the user and allows the translator to properly handle streaming the file to the user.
When a file by that path cannot be found it will throw an exception.
NOTE Whenever this method is called it will supersede any other output that has been queued to be sent to the user
by using add()
or set()
. Unless the translator is capable of sending multipart responses.
Example
exports.name = 'myAction'
exports.description = 'Example Action'
exports.run = function(apx,req,res,next){
res.sendFile('/tmp/foo','home.html',{tmpFile: true}) //setting tmpFile to true will delete the file after sending
next()
}
In order for translators to properly handle sending data to their clients there are 3 scenarios which apply to how the render function will respond.
In this example the output will simply be logged to the console.
var xml = require('xml')
, fs = require('fs')
, Response = require('apx/lib/Response')
, res = new Response()
//create our response handler
var responseHandler = function(err,response){
if(err) throw err
if('object' === response.format){
if('text/json' === response.mimeType){
console.log(JSON.stringify(response.data))
} else if('text/xml' === response.mimeType){
console.log(xml(response.data))
} else {
console.warn('desired output type of ' + response.mimeType + ' is not supported defaulting to JSON')
console.log(JSON.stringify(response.data))
}
} else if('raw' === response.format){
console.log(response.body)
} else if('file' === response.format){
var stream = fs.createReadStream(response.file.path)
stream.on('readable',function(){
var chunk
while(null !== (chunk = stream.read())){
console.log(chunk)
}
}
} else {
console.warn('desired output format of ' + response.format + ' is not supported, not sending output')
}
}
//implement the handler
res.render(responseHandler)
pre
and post
middleware translators need to fire the Response.render()
method and then send
the rendered response to their clientResponse.sendFile(path)
to allow sending of files to the user. Using this method still requires calling next()
and will supersede any existing output.Response.success()
and Response.error()
to accept a better combination of arguments to produLanguage | javascript |
Version | 0.7.2 |
Git URL | https://github.com/nullivex/apx |
License | MIT |
Description | Modular extensible API framework |
Keywords |