Make requests that are representative of HTTP requests to a function.
Get responses that are representative of HTTP responses.
Accepts connect middleware.
Easier to test your server code (using direct function calls).
Faster to test your server code (no HTTP required).
Can be wrapped by any server.
Logs and profiling grouped by request.
Example
The sans-server package is a tool for building a functional web server that is independent of networking. As a functional library, requests can be made to it and responses provided by it.
const SansServer = require('sans-server');// create a server instanceconst server = SansServer();// add middleware to the serverserver.use(function(req, res, next) { if (req.path === '/') { res.send('OK'); } else { next(); }});// make a request against the serverserver.request({ path: '/' }, function(err, response) { console.log(response.statusCode); // 200 console.log(response.body); // 'OK'});// make a request against the serverserver.request({ path: '/foo' }, function(err, response) { console.log(response.body); // 'Not Found' console.log(response.statusCode); // 404});// make a request using a promiseserver.request({ path: '/' }) .then(function(response) { console.log(response.statusCode); // 200 console.log(response.body); // 'OK' });
A boolean that specifies whether the grouped logs should be output at the end of a request.
boolean
true
rejectable
A value that specifies if request promises should be rejected or automatically caught. If set to false then requests will always return a valid response.
boolean
false
timeout
The number of seconds to wait prior to request timeout. Set this value to zero to disable the timeout.
number
30
useBuiltInHooks
A boolean specifying whether built in hooks should run for each request. This includes request method validation and response transformation. If set to false the built in hooks can still be added manually.
The type of hook to apply the hook function to. Out of the box this package has a request and response hook, but other packages or modules can add to the list of available hooks.
string
weight
The weight of the hook(s) being added. A lower number means the hook will run sooner and a higher number means it will run later. Negative numbers are allowed.
number
0
hook
A hook function. Naming the function will improve log readability. Any number of hook functions can be defined at once.
function
Returns The current SansServer instance.
Example: Single Hook
const SansServer = require('sans-server');const server = SansServer();server.hook('request', function myHook(req, res, next) { // run some logic here... next();});
Example: Multiple Hooks
const SansServer = require('sans-server');const server = SansServer();server.hook('request', hook1, hook2);function hook1(req, res, next) { // run some logic here... next();}function hook2(req, res, next) { // run some logic here... next();}
Example: Single Hook that Runs Earlier
const SansServer = require('sans-server');const server = SansServer();server.hook('request', -100, function myHook(req, res, next) { // run some logic here... next();});
Define a unique hook type. Attempting to define a second hook with the same name will throw an error.
SignatureSansServer#hook.define ( type ) : Symbol
Parameters
Parameter
Description
Type
Default
type
The hook type to define.
string
Returns a symbol that must be used to execute all hook functions that have subscribed to this hook chain.
Example
const SansServer = require('sans-server');const server = SansServer();// define custom hookconst key = server.hook.define('my-hook');// during the request you can execute your custom hookserver.use(function myHook(req, res, next) { req.hook.run(key, next);});
A function to call when the request has been completed. The callback receives any error as its first parameter. The response state is provided as the second parameter whether there was an error or not.
function
Request Configuration
Option
Description
Type
Default
body
The body of the request. This can be any data type, generally a primitive or a plain object is recommended. If the body contains a form payload then it should follow the request body documentation.
''
headers
The request headers. This needs to be an object with string keys mapped to string values. For example: { headers: { 'content-type', 'plain/text' } }.
object
{}
method
The request method. Must be one of 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'. Case is not important.
string
'GET'
query
The query string parameters. If a string then it will be parsed. If an object then each key must be a string and each value must be either a string, true, or an array of strings.
objectstring
{}
path
The path for the request. The path should not include the protocol, domain, or port information. The path may contain query parameters and those will be pushed into the request query object automatically.
string
''
Request Body
If the body is an object then it can be used to represent one of several content types: application/json, application/x-www-form-urlencoded, or multipart/form-data.
The type that the object represents is determined by the Content-Type header. If the body is an object and the Content-Type header is either application/x-www-form-urlencoded or multipart/form-data then the object should be in form body format.
Form body format is used when the body represents a submitted form, whether via application/x-www-form-urlencoded or multipart/form-data.
const SansServer = require('sans-server');const server = SansServer();server.request('/get/some/path', function(err, res) { if (err) console.error(err.stack); console.log(res.body); // the response body console.log(res.cookies); // an object with the set cookies console.log(res.headers); // an object with the set headers console.log(res.rawHeaders); // an array of all headers and cookies serialized console.log(res.statusCode); // the response status code});
Promise Example
const SansServer = require('sans-server');const server = SansServer();server.request('/get/some/path') .then(function(res) { console.log(res.body); // the response body console.log(res.cookies); // an object with the set cookies console.log(res.headers); // an object with the set headers console.log(res.rawHeaders); // an array of all headers and cookies serialized console.log(res.statusCode); // the response status code }) .catch(function(err) { console.error(err.stack); });
Add a middleware hook to each request. This works the same as connect middleware and is equivalent to calling sansServer.hook('request', 0, myMiddlewareFunction). For an explanation on hooks see Hooks and Middleware.
A static method that is best used early in the request hooks. It validates that the HTTP method is one of (case insensitive) 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'.
This method is automatically used as a request hook with weight -100000 if the SansServer configuration options has useBuiltInHooks set to true. Otherwise you can add the hook manually like this:
Example
const SansServer = require('sans-server');// create the Sans Server instance without using built in hooksconst sansServer = SansServer({ useBuildInHooks: false });// add validate method request hooksansServer.hook('request', -100000, SansServer.hooks.validateMethod);
A static method that is best used late in the response hook.
This method will automatically set the Content-Type header if not set and it will transform the body into a string.
This is how the conversions are made. Content-Type is only modified if unset, unless otherwise specified below.
Body Type
Sets Content-Type To
Body Transformation
Error
Always 'text/plain'
'Internal Server Error'
Buffer
'application/octet-stream'
Convert to base64 encoded string.
Object
'application.json'
Convert using JSON.stringify
string
'text/html'
None
Anything else
'text/plain'
Convert using String()
Example
const SansServer = require('sans-server');// create the Sans Server instance without using built in hooksconst sansServer = SansServer({ useBuildInHooks: false });// add validate method request hooksansServer.hook('request', -100000, SansServer.hooks.transformResponse);
This constructor is invoked when calling SansServer#request and an instance of this constructor is returned by that function. This constructor cannot be invoked directly.
Because the request instance extends the Promise you can also use then and catch although the promise will never be rejected so you can skip using the catch function.
ExtendsEventEmitterPromise
Methods
catch - Catch any request processing errors. If the Sans Server rejectable is not set to true then this method is useless.
then - Assign a callback for the resolved promise.
Properties
body - Get or set the request body.
headers - Get or set the request headers.
id - Get the unique request ID.
method - Get or set the request method.
path - Get or set the request path.
query - Get or set the request query parameters.
res - Get the Response instance tied to this request.
server - Get a reference to the Sans Server instance that made this request.
url - Get the request URL, a combination of the path and query string parameters.
Events
Unless otherwise noted, each of these events provide the Response instance with the event.
error - Fires when an error occurs and provides the error as event data.
log - Fires when a message is logged and provides the following structure as it's event data: { action: string, category: string, details: object, message: string, timestamp: number }.
res-clear-header - Fired when a header is cleared.
res-complete - Fires after res-send event and after all response hooks have completed.
res-reset - Fires when the body, status code, headers, and cookies have all been reset to empty.
res-send - Fires when the Response#send function has been called.
res-set-body - Fired when the body has been modified.
res-set-cookie - Fired when a cookie is set or cleared.
res-set-header - Fired when a header is set.
res-set-status - Fired when the status code changes.
res-state-change - Fired when any of the response state has been modified.
Note, the request will never be rejected so any handler you define here will never be called. In the case of an error the request will still be resolved to a response with a 500 status code.
SignatureRequest#catch ( onRejected ) : Response
Parameters
Parameter
Description
Type
Default
onRejected
The function to call in case of promise rejection.
An optional function that will be called after executing all hooks. If an error occurs this function will receive that as its first parameter, otherwise it will not receive a parameter.
function
Returns a Promise if the next function was not provided as a parameter.
Example
const SansServer = require('sans-server');const sansServer = SansServer();// define a custom hookconst key = sansServer.hook.define('custom-hook');// define a hook function for the response hooksansServer.hook('response', 0, function(req, res, next) { // run the custom-hook hooks in reverse before calling next hook req.hook.reverse(key, next);});
An optional function that will be called after executing all hooks. If an error occurs this function will receive that as its first parameter, otherwise it will not receive a parameter.
function
Returns a Promise if the next function was not provided as a parameter.
Example
const SansServer = require('sans-server');const sansServer = SansServer();// define a custom hookconst key = sansServer.hook.define('custom-hook');// define a hook function for the response hooksansServer.hook('response', 0, function(req, res, next) { // run the custom-hook hooks in reverse before calling next hook req.hook.run(key, next);});
Produce a logging function. The returned function can be called to produce standardized log events. This function is used to produce the log function for the both the Request and Response.
SignatureRequest#logger (category, type, [ returnValue ]) : Function
Parameters
Parameter
Description
Type
Default
category
A short string that describes the overarching code that is producing the log function. A good option for this value would be the name of the NodeJS package producing the log function.
string
type
A classification that describes the subset of code that is producing the log function. A good option for this value would be the name of the module of code that is producing the log function.
string
returnValue
A value to run when the log function is called. Ideal for property chaining.
Any
undefined
Returns the log producing function. The function can be called with any parameters and will format the logged data similar to the console.log function, but this function will have the advantage of logging with the Debug package as well as grouping logs for a single request.
Example
This example is trivial and a bit of a waste. It would generally make more sense to produce a log function for a complex middleware that implements it's own sans-server-middleware.
const SansServer = require('sans-server');const server = SansServer();server.use(function myMiddleware(req, res, next) { const log = req.logger('my-package-name', 'this-module-name'); log('This is a number %d', 5);});
Add fulfillment or rejection handlers to the request promise.
Note, the request will never be rejected so it is a waste to provide an onRejected parameter. In the case of an error then request will be resolved to a response with a 500 status code.
This constructor is invoked when calling SansServer#request and an instance of this constructor is attached to the Request instance. This constructor cannot be invoked directly.
req : Request - Get the request object that is associated with this response object.
sent : boolean - Get whether the request has already been sent.
server : SansServer - Get the SansServer instance tied to this request.
state : object - Get the current response state. See response state for details.
statusCode : number - Get or set the current response status code.
Hooks
response - Runs in reverse when the response is sent. Lower weights will still run first, but two functions of equal weight will run in reverse order from when they were set.
Response State
The response state is an object that represents the response at the point in time it was requested. It can be acquired using the Response#state` getter.
The value to set the body to. This value can be set to anything but once all response hooks have run it will be converted to either a string, a Buffer, or a plain object.
A detailed object that contains information that contains information relative to the logged message. This object could be used by log event handlers that want to parse the log data.
A hook defines the logic that each request passes through to determine its result. Middleware is a type of hook that runs with the incoming request. Technically you could do anything with the middleware hooks, but it may require rewriting or extending existing functions. To ease development Sans Server enables the use of additional hooks and the ability to create new hooks.
There are two types of hooks:
Standard - these hooks are called when there are no errors. They receive three parameters: 1) the Request, 2) the Response, and 3) the next function.
function myHook(req, res, next) { // do some logic next();}
Error Handling - these hooks are only called when there are errors. They receive four parameters: 1) the Error, 2) the Request, 3) the Response, and 4) the next function.
function myErrorHook(req, res, next) { // do some logic next();}
When you define a hook the number of parameters in your hook function is used to determine if it is for handling errors or not.
Next
Hooks commonly run as a chain of functions, one runs, followed by another, and so on. The next function is the mechanism used for continuing on to the next hook in line. By calling next() within your hook you are signifying that the hook is done processing.
If during processing an error occurs you have two options: 1) throw the error (synchronous only) or 2) pass the error to the next function (synchronous or asynchronous).
function myHook(req, res, next) { // do some logic throw Error('Oh no! An error.');}
function myHook(req, res, next) { // do some logic next(Error('Oh no! An error.'));}
Hook Flow
If you have a hook that produces an error then all non-error handling hooks will be skipped until an error handling hook is found.