npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

weare-ajax-response

v2.1.2

Published

Format AJAX responses based on WE_ARE's JSend derivative, see https://bitbucket.org/weare/jsend/wiki

Downloads

5

Readme

Agence WE_ARE
Repository https://npm.dev.studioweare.com

WE_ARE AJAX Response

Format AJAX responses, see WE_ARE's JSend derivative.

Installation

$ npm install weare-ajax-response

Usage

var express = require('express')
var ajaxResponse = require('weare-ajax-response');

var app = express();

app.get('/a-json-success-response', function(req, res) {
  ajaxResponse(res).ok();
});

Use it as a function

You can use ajaxResponse as a function to automatically send your response by passing the Express res object directly to it.

This method is useful if you just want to directly send a response.

app.get('/a-json-object-response', function(req, res) {
  ajaxResponse(res).success({ foo: 'bar' });
});

Use it as an object

You can create an instance of ajaxResponse, set his status and data and send it later, when you'll have access to the Express.js' res (response) object for example.

This method is useful when you want to pass an already setted response to a callback. This way, you can pass an error response to the err argument of a callback and send it directly when you execute the callback in you router.

app.get('/proccess-and-fail', function(req, res) {
  var processSomethingAndFail = function (callback) {
    var fail = true;
    if (fail)
      callback(new ajaxResponse.badRequest());return;

    callback(null, 'Everything is fine!');
  };

  processSomethingAndFail(function (err, data) {
    if (err) {
      err.send(res);return;
    }
    // This is the "function" way of sending the response...
    ajaxResponse(res).success(data);
    // ...this is the "object" way which produce the same result:
    // new ajaxResponse.success(data).send(res);
  });
});
Access instance data

An instance of ajaxResponse has 5 functions to get his data:

  • ajaxResponse.status();
  • ajaxResponse.code();
  • ajaxResponse.message();
  • ajaxResponse.data();
  • ajaxResponse.httpStatus();

Status functions

To send a response, 3 primary functions are defined, following the jSend standard.

Success

Param data mixed (optional, default to null)
Param httpStatus Number (optional, in the 2xx range, default to 200)

"function" method
ajaxResponse(res).success(data, httpStatus);
"object" method
new ajaxResponse.success(data, httpStatus).send(res);
Result

HTTP status code (if used): 200

{
  "status": "success",
  "data": null
}
Fail

Param data mixed (optional, default to null)
Param httpStatus Number (optional, in the 4xx range, default to 400)

"function" method
ajaxResponse(res).fail(data);
"object" method
new ajaxResponse.fail(data, httpStatus).send(res);
Result

HTTP status code (if used): 400

{
  "status": "fail",
  "fail": null
}
Error

Param message String (optional, default to '')
Param code Number (optional)
Param data mixed (optional, default to null)
Param httpStatus Number (optional, in the 5xx, default to 500)

"function" method
ajaxResponse(res).error(message, code, data, httpStatus);
"object" method
new ajaxResponse.error(message, code, data, httpStatus).send(res);
Result

HTTP status code (if used): 500

{
  "status": "error",
  "error": {
    "message": ""
  }
}

With params:

ajaxResponse(res).error('dbclient error communicating with server', 10278, { mongoError: { msg: 'dbclient error communicating with server' } }, 500);

HTTP status code (if used): 500

{
  "status": "error",
  "error": {
    "message": "dbclient error communicating with server",
    "code": 10278,
    "data": {
      "mongoError": {
        "msg": "dbclient error communicating with server"
      }
    }
  }
}

Helpers functions

You can use helpers functions to automatically set the status and HTTP status code. They're based on the list of HTTP status code you'll see below.

If you don't specify a data for success and fail or a message for error, the description of the HTTP status code will be used.

"function" method
ajaxResponse(res).methodNotAllowed(data);
// or
ajaxResponse(res).http405(data);
"object" method
new ajaxResponse.methodNotAllowed(data).send(res);
// or
new ajaxResponse.http405(data).send(res);
Result

HTTP status code (if used): 405

{
  "status": "fail",
  "fail": "Method Not Allowed"
}
HTTP status code supported
Success
  • 200: http200, ok
  • 201: http201, created
  • 202: http202, accepted
  • 203: http203, nonAuthoritativeInformation
  • 204: http204, noContent
  • 205: http205, resetContent
  • 206: http206, partialContent
Fail
  • 400: http400, badRequest
  • 401: http401, unauthorized
  • 402: http402, paymentRequired
  • 403: http403, forbidden
  • 404: http404, notFound
  • 405: http405, methodNotAllowed
  • 406: http406, notAcceptable
  • 407: http407, proxyAuthenticationRequired
  • 408: http408, requestTimeOut
  • 409: http409, conflict
  • 410: http410, gone
  • 411: http411, lengthRequired
  • 412: http412, preconditionFailed
  • 413: http413, requestEntityTooLarge
  • 414: http414, requestUriTooLarge
  • 415: http415, unsupportedMediaType
  • 416: http416, requestedRangeNotSatisfiable
  • 417: http417, expectationFailed
  • 422: http422, unprocessableEntity
  • 429: http429, tooManyRequests
Error
  • 500: http500, internalServerError
  • 501: http501, notImplemented
  • 502: http502, badGateway
  • 503: http503, serviceUnavailable
  • 504: http504, gatewayTimeOut
  • 505: http505, httpVersionNotSupported

Chainable

These 4 examples will produces the same results:

ajaxResponse(res).fail({ teapot: 'Empty, make some more.' }, 418);
ajaxResponse(res)
  .httpStatus(418)
  .fail({ teapot: 'Empty, make some more.' });
ajaxResponse(res)
  .data({ teapot: 'Empty, make some more.' })
  .httpStatus(418)
  .fail();
ajaxResponse(res)
  .data('This data will be override.')
  .httpStatus(200)
  .fail({ teapot: 'Empty, make some more.' }, 418);

Settings

You can set ajaxResponse to send true HTTP status codes. It's deactivated by default so 200 HTTP status code is always sent.

// Enable or disable enhanced HTTP mode (true or false).
ajaxResponse.setTrueHttpStatusCodes(true);