1.0.6 • Published 8 years ago

es6-api-envelope v1.0.6

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
8 years ago

API Envelope

NPM version Build Status codecov.io

Constructs a simple Data Envelope to return a standardized format of JSON data for use in XHR or Fetch requests to an API. Wraps the intended response from the server attaching meta data and any client messaging along with it.

The envelope is broken down into three main objects, referenced as keys in the envelope.
They are as follows:

  • meta
    The meta data of the envelope contains the status code of the envelope in all cases. In the case of an error, the meta data will contain error information as well.

    • code
      Number: status code of envelope (success and error)

    • errorType
      String: type of error (error only)

    • errorDetail
      Array: list of error messages

  • notifications
    The notifications data contains any potential messaging to be displayed to the client. The notifications object is a Collection (Array of Objects) of notification objects.

  • response
    The response data contains the data you wish to send back to the client as a response. This member will not be present in Error envelopes, and will be present in Success envelopes.

Usage

To use the envelope simply get a new instance, or reset an existing one. From there simply call the type of envelope you'd like to return, optionally adding notifications if needed.

/**********************************************
*               Import Envelope               *
**********************************************/

import Envelope from 'es6-api-envelope';


/**********************************************
*      Create Instance / Recycle Instance     *
**********************************************/

// create new instance
let envelope = new Envelope();

// recycle existing instance
envelope.reset();


/**********************************************
*            Send Success Envelope            *
**********************************************/

// sends an empty success envelope, 
// 200 is the implied status code
envelope.success();

// 200 is the implied status code
envelope.success( { foo: 'bar' } );

// custom status code
envelope.success( { foo: 'bar' }, [Number] );


/**********************************************
*             Send Error Envelope             *
**********************************************/

// error envelope with a status code of 400, 
// and default errorType and errorDetails members
envelope.error( 400 ); 

// error envelope with custom errorType and errorDetails
envelope.error( 
    400, 
    {
        errorType: 'lil_brudder',
        errorDetails: [ 'fhqwhgads' ],
    }
); 

// one options argument supplied.
// code and custom errorType/errorDetails all wrapped in options object
envelope.error(
    {
        errorCode: 400,
        errorType: 'cheat error',
        errorDetails: [ 'the system is down!' ],
    }
);


/**********************************************
*        Add Notifications to Envelope        *
**********************************************/

// add notifications object to list of notifications
// append to list is implied
envelope.notify( {
    type: 'info',
    message: 'foo'
} );

// add notification object to list of notifications
// overwriting list with only this notification
envelope.notify( {
    type: 'info',
    message: 'foo'
}, true );

// add notification message to list of notifications
// append to list is implied
envelope.notify( 'Foo!' );

// add notification message to list of notifications
// overwriting list with only this notification
envelope.notify( 'Foo!', true );

Success

Success envelopes can be created by calling success().
A success envelope is called by supplying the data to return and an optional status code. A success envelope is assumed to have a status code of 200, if you wish to return a differnt code, supply this argument.

// implied 200 status code
envelope.success( { foo: 'bar' } );

// explicit status code
envelope.success( { foo: 'bar' }, 200 );

/*
both above return:
{
    meta: {
        code: 200
    },
    response: {
        foo: 'bar'
    }
}
*/

// bc you can
envelope.success( { foo: 'bar' }, 201 );

/*
returns:
{
    meta: {
        code: 201
    },
    response: {
        foo: 'bar'
    }
}
*/

// empty success
envelope.success();
/*
returns:
{
    meta:{
        code: 200
    },
    response: {}
}
*/

Error

Error envelopes can be created by calling error().
An error envelope is called by supplying one of the following combinations:

  • only an error code, the errorType and errorDetails use code defaults
  • an error code and an options object containing errorType and errorDetails
  • only an options object containing error code, errorType, and errorDetails
// only send error code, using code defaults
envelope.error( 400 );
/*
returns:
{
    meta:{
        code: 400,
        errorType: 'param_error',
        errorDetails: [ 'A required parameter was missing or a parameter was malformed.' ],
    }
}
*/

// send code and options
envelope.error( 
    400, 
    {
        errorType: 'lil_brudder',
        errorDetails: [ 'fhqwhgads' ],
    }
);
/*
returns:
{
    meta:{
        code: 400,
        errorType: 'lil_brudder',
        errorDetails: [ 'fhqwhgads' ],
    }
}
*/

// send only options object
envelope.error(
    {
        errorCode: 400,
        errorType: 'cheat error',
        errorDetails: [ 'the system is down!' ],
    }
);
/*
returns:
{
    meta:{
        code: 400,
        errorType: 'cheat error',
        errorDetails: [ 'the system is down!' ],
    }
}
*/


// empty error
envelope.error();
/*
returns:
{
    meta:{
        code: 400,
        errorType: 'param_error',
        errorDetails: [ 'A required parameter was missing or a parameter was malformed.' ],
    }
}
*/

Notify

Adding notifications to an envelope can be done by calling notify().
Notifications are an Array of notification messages. Notification messages, by defauly, are appended to the array of notifications. Add the optional second parameter to true to overwrite Array with this notification message. A notification message, currently, can be a String or an Object containing level, and message members.

NOTE: This is subject to change as its currently an issue labeled discussion/enhancement.

// append notifications message to list of notifications
envelope.notify( {
    type: 'info',
    message: 'foo'
} );
/*
returns:
{
    meta: {
        ... success|failure meta object ...
    },
    ... possible response object if success...
    notifications: [
        ...,
        {
            type: 'info',
            message: 'foo'
        }
    ]
}
*/

// overwrite notifications with this notifications message
envelope.notify( {
    type: 'info',
    message: 'foo'
}, true );
/*
returns:
{
    meta: {
        ... success|failure meta object ...
    },
    ... possible response object if success...
    notifications: [
        {
            type: 'info',
            message: 'foo'
        }
    ]
}
*/

// append notifications message to list of notifications
envelope.notify( 'Foo!' );
/*
returns:
{
    meta: {
        ... success|failure meta object ...
    },
    ... possible response object if success...
    notifications: [
        ...,
        'Foo!'
    ]
}
*/

// overwrite notifications with this notifications message
envelope.notify( 'Foo!', true );
/*
returns:
{
    meta: {
        ... success|failure meta object ...
    },
    ... possible response object if success...
    notifications: [
        Foo!
    ]
}
*/

Default Status Codes

There are static methods to return status code specific information should you need it. They are as defined as such:

// return entire status codes constant. 
// Note: the call is on the class, not the instance.
Envelope.statusCodes();
/*
returns:
{
    200: {
        code: 200,
    },
    400: {
        code: 400,
        errorType: 'param_error',
        errorDetails: [ 'A required parameter was missing or a parameter was malformed.' ],
    },
    401: {
        code: 401,
        errorType: 'invalid_auth',
        errorDetails: [ 'OAuth token was not provided or was invalid.' ],
    },
    403: {
        code: 403,
        errorType: 'not_authorized',
        errorDetails: [ 'User is not authorized to take this action.' ],
    },
    404: {
        code: 404,
        errorType: 'endpoint_error',
        errorDetails: [ 'The requested path does not exist.' ],
    },
    405: {
        code: 405,
        errorType: 'not_allowed',
        errorDetails: [ 'Attempting to use POST with a GET-only endpoint, or vice-versa.' ],
    },
    409: {
        code: 409,
        errorType: 'conflict',
        errorDetails: [ 'The request could not be completed as it is.' ],
    },
    451: {
        code: 451,
        errorType: 'censored',
        errorDetails: [ 'The request could not be completed due to legal reasons.' ],
    },
    500: {
        code: 500,
        errorType: 'internal_error',
        errorDetails: [ 'The server is experiencing melancholy.' ],
    },
}
*/

// return  a specific status code from the constant. 
// Note: the call is on the class, not the instance.
Envelope.statusCode( 451 )
/*
returns:
{
    code: 451,
    errorType: 'censored',
    errorDetails: [ 'The request could not be completed due to legal reasons.' ],
}
*/

Optional getters

Getters and Setters are provided for the following members:

  • get metadata
    returns the current meta object of the envelope instance

  • get notificationsData
    returns notifications list of the envelope instance

  • get responseData
    returns the response data of the envelope instance

Testing

Unit Tests

Tests save unicorns.
Unit tests are under ./test, and are written using a node implementaion of TAP.
There are a number of unit tests provided with the envelope.
To run tests:
npm test
...Think of the unicorns.

Code Coverage

Code coverage is provided by nyc. The following commands pertain to coverage:

  • npm run coverage
    generates an HTML coverage report located: ./coverage/lcov-report/index.html

  • npm run covReport
    outputs the results of the latest coverage report

codecov.io

1.0.6

8 years ago

1.0.5

8 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago