npm.io
1.3.1 • Published 3 years ago

restponses

Licence
MIT
Version
1.3.1
Deps
0
Size
305 kB
Vulns
0
Weekly
0
Stars
2

Restponses

Restponses is a library that allows you to easily generate clear and concise responses for your APIs. If your project is small, you don't have so clear your business rules, or you just don't want to worry about status codes, default messages and the nomenclature of the fields of your endpoints responses, then Restponses is for you :).

Get Started


First you need to install the dependency.

npm install restponses

Restponses has been developed totally with typescript, so you don't have to worry about installing any @types dependencies.

Then you will need to import the base methods to generate your response, you have five options for five status codes types:

import { 
  Response1xxInformative,
  Response2xxSuccessful, 
  Response3xxRedirection, 
  Response4xxClientError, 
  Response5xxServerError 
  } from "restponses"

Base Methods Parameters

1. StatusCode Param

The most simpliest way to use these methods is entering the only mandatory parameter, this is the status code for your response. In this way, they will return the minimum default values for each status code, for example, look at this request made with express:

  app.get("/potatoes/:id", (req, res) => {
    const {id} = req.params
    if(!id){
      //Example 1 (400BadRequest)
      return res.json(Response4xxClientError("400BadRequest"))
    }
    try {
      const potato = dbGetPotato(id)
      if(!potato){
        // Example 2 (404NotFound)
        return res.json(Response4xxClientError("404NotFound"))
      }else{
        // Example 3 (200Ok)
        return res.json(Response2xxSuccessful("200Ok"))
      }
    } catch (error) {
      // Example 4 (500InternalServerError)
      return res.json(Responses5xxServerError("500InternalServerError"))
    }
  })

The outputs would be these:


// Example 1
{
  httpStatus: 400,
  serverMessage: 'Bad Request',
  error: true,
  success: false
}

// Example 2
{
  httpStatus: 404,
  serverMessage: 'Not Found',
  error: true,
  success: false
}

// Example 3
{
  httpStatus: 200,
  serverMessage: 'OK',
  detail: 'The request has been successfully processed',
  success: true,
  error: false
}

// Example 4
{
  httpStatus: 500,
  serverMessage: 'Internal Server Error',
  error: true,
  success: false
}
2. Input parameter

You can also overwrite the fields serverMessage and detail with custom information using the second parameter: input. You can even add information about the consulted resource, data obtained or details of errors in the same way:

Response1xxInformative("100Continue", { consultedResource: "/getPotato", serverMessage: "/getPotato consulted", detail: "please continue"})

  //Output
  {
    httpStatus: 100,
    serverMessage: '/getPotato consulted',
    detail: 'please continue',
    consultedResource: '/getPotato'
  }


Response2xxSuccessful("200Ok", { consultedResource: "/getPotato", data: dbResponse, serverMessage: "Potato was found", detail: "now you can eat potato" })

  // Output
  {
    httpStatus: 200,
    serverMessage: 'Potato was found',
    data: {
      id: 45322,
      name: "Yellow potato",
      country: "Peru"
    }
    detail: 'now you can eat potato',
    consultedResource: '/getPotato',
    success: true,
    error: false
  }

  Response3xxRedirection("300MultipleChoices", { consultedResource: "/getPotato", detail: "Potato was found, but you can't eat it now", serverMessage: "Potato was found, now choose one" })

  // Output
  {
    httpStatus: 300,
    serverMessage: 'Potato was found, now choose one',
    detail: "Potato was found, but you can't eat it now",
    consultedResource: '/getPotato'
  }

  Response4xxClientError("404NotFound", { consultedResource: "/getPotato", detail: "Potato was not found", serverMessage: "Potato was not found", errorCode: "404NOTFOUND", errorName: "PotatoNotFound", errorDescription: "Your resource was not found" })
  
  // Output
  {
    httpStatus: 404,
    serverMessage: 'Potato was not found',
    consultedResource: '/getPotato',
    errors: undefined,
    errorCode: '404NOTFOUND',
    errorName: 'PotatoNotFound',
    errorDescription:'Your resource was not found',
    error: true,
    success: false
  }

  Response5xxServerError("500InternalServerError", { consultedResource: "/getPotato", serverMessage: "Potato was not found due to a server error", errorCode: "500SERVERERROR", errorName: "INTERNAL_SERVER_ERROR" })

  // Output
  {
    httpStatus: 500,
    serverMessage: 'Potato was not found due to a server error',
    consultedResource: '/getPotato',
    errorCode: '500SERVERERROR',
    errorName: 'INTERNAL_SERVER_ERROR',
    error: true,
    success: false
  }
3. StatusOptions parameter

The third and last parameter, statusOptions params allows you introduce specific field/s related to the status code of your response. For example, if you want to add the url where is your created resource (201), or the not found URL or resource (404), you can simply use the corresponding StatusOption method. You just have to import the class and access the desired method:

import { StatusOptions } from "restponses"

Response2xxSuccessful("201Created", { consultedResource: "/createPotato", serverMessage: "Potato created" }, StatusOptions.Status201Opt("https://potato.api/34"))

//Output
  {
    httpStatus: 201,
    serverMessage: 'Potato created',
    detail: 'Resource successfully created',
    consultedResource: '/createPotato',
    success: true,
    error: false,
    location: 'https://potato.api/34'
  }

Base methods


As you read above, Restponses gives you five base methods to generate responses according to the status code to return:

Method Description
Response1xxInformative Generates informative responses with status codes 100
Response2xxSuccessful Generates successful responses with status codes 200
Response3xxRedirection Generates redirection responses with status codes 300
Response4xxClientError Generates client side error responses with status codes 400
Response5xxServerError Generates server side error responses with status codes 500
Response1xxInformative()
Params:
Name Type Attribute Description
statusCode StatusCode1xx
  • Mandatory
Status code of your response.
Supported:
  • "100Continue": 100
  • "101SwitchingProtocols": 101
  • "102Processing": 102
  • "103EarlyHints": 103
input BaseInput
  • Optional
Base input object
input.consultedResource string
  • Optional
Url or name of the resource that was consulted
input.detail string
  • Optional
  • Default (only 100)
Detail of the response
input.serverMessage string
  • Optional
  • Default
serverMessage that the server will send to the client
Example:
Response1xxInformative(statusCode: "100Continue", input: { consultedResource: "potato/getPotato" })

// Output
{
  httpStatus: 100,
  serverMessage: 'Continue',
  detail: 'Continue with the request',
  consultedResource: 'potato/getPotato'
}
Response2xxSuccessful()
Params:
Name Type Attribute Description
statusCode StatusCode2xx
  • Mandatory
Status code of your response.
Supported:
  • "200OK": 200
  • "201Created": 201
  • "202Accepted": 202
  • "203NonAuthoritativeInformation": 203
  • "204NoContent": 204
  • "205ResetContent": 205
  • "206PartialContent": 206
  • "207MultiStatus": 207
  • "208AlreadyReported": 208
  • "226IMUsed": 226
input BaseSuccessfulInput
  • Optional
Base successful input object
input.consultedResource string
  • Optional
URl or name of the consulted resource
input.data any
  • Optional
Data that the server will send to the client
input.detail string
  • Optional
  • Default
Detail of the response
input.serverMessage string
  • Optional
  • Default
Message that the server will send to the client
statusOptions Response2xxOpt
  • Optional
Methods that you could use to add specific fields in your response related to the status code
Example:

Output includes success and error fields by default.

Response2xxSuccessful("200Ok", { consultedResource: "/getPotato" })

// Output
{
  httpStatus: 200,
  serverMessage: 'OK',
  detail: 'The request has been successfully processed',
  consultedResource: '/getPotato',
  success: true,
  error: false
}
Status options:
Method Params Description
Status201Opt
  • location: string
Status202Opt
  • requestId: string
Status203Opt
  • source: ISource203
  • source.name: string
  • source.description: string (optional)
  • source.url: string (optional)
Status207Opt
  • states: IBasicState207[]
  • httpStatus: number
  • serverMessage: string
  • detail: string (optional)
Response3xxRedirection()
Params:
Name Type Attribute Description
statusCode StatusCode3xx
  • Mandatory
Status code of your response.
Supported:
  • "300MultipleChoices": 300
  • "301MovedPermanently": 301
  • "302Found": 302
  • "303SeeOther": 303
  • "304NotModified": 304
  • "305UseProxy": 305
  • "307TemporaryRedirect": 307
  • "308PermanentRedirect": 308
input BaseInput
  • Optional
Base input object
input.consultedResource string
  • Optional
URL or name of the resource that was consulted
input.detail string
  • Optional
Detail of the response
input.serverMessage string
  • Optional
  • Default
Message that the server will send to the client
statusOptions Response3xxOpt
  • Optional
Methods that you could use to add specific fields in your response related to the status code
Example:
Response3xxRedirection("301MovedPermanently", { consultedResource: "/getPotato", detail: "You can found the resource consulting at: '/getPot' endpoint" })

// Output
{
  httpStatus: 301,
  serverMessage: 'Moved Permanently',
  detail: "You can found the resource consulting at: '/getPot' endpoint",
  consultedResource: '/getPotato'
}
Status options:
Method Params Description
Status300Opt
  • options: Array
Status301Opt
  • sources: ISources301
  • sources.oldSource: string
  • sources.newSource: string
Status302Opt
  • redirectUrl: string
Status303Opt
  • redirectUrl: string
Status305Opt
  • proxyUrl: string
Status307Opt
  • redirectUrl: string
Status308Opt
  • redirectUrl: string
Response4xxClientError()
Params:
Name Type Attribute Description
statusCode StatusCode4xx
  • Mandatory
Status code of your response.
Supported:
  • "400BadRequest": 400
  • "401Unauthorized": 401
  • "402PaymentRequired": 402
  • "403Forbidden": 403
  • "404NotFound": 404
  • "405MethodNotAllowed": 405
  • "406NotAcceptable": 406
  • "407ProxyAuthenticationRequired": 407
  • "408RequestTimeout": 408
  • "409Conflict": 409
  • "410Gone": 410
  • "411LengthRequired": 411
  • "412PreconditionFailed": 412
  • "413PayloadTooLarge": 413
  • "414URITooLong": 414
  • "415UnsupportedMediaType": 415
  • "416RangeNotSatisfiable": 416
  • "417ExpectationFailed": 417
  • "418ImATeapot": 418
  • "421MisdirectedRequest": 421
  • "422UnprocessableEntity": 422
  • "423Locked": 423
  • "424FailedDependency": 424
  • "425TooEarly": 425
  • "426UpgradeRequired": 426
  • "428PreconditionRequired": 428
  • "429TooManyRequests": 429
  • "431RequestHeaderFieldsTooLarge": 431
  • "451UnavailableForLegalReasons": 451
input BaseErrorInput
  • Optional
Base error input object
input.consultedResource string
  • Optional
URL or name of the resource that was consulted
input.detail string
  • Optional
Detail of the response
input.serverMessage string
  • Optional
  • Default
Message that the server will send to the client
input.errorCode string
  • Optional
Error identifier code
input.errorDescription string
  • Optional
Error description
input.errorName string
  • Optional
Error name
input.errors any
  • Optional
Arbitrary errors you can add to your response
statusOptions Response4xxOpt
  • Optional
Methods that you could use to add specific fields in your response related to the status code
Example:

Output includes success and error fields by default.

Response4xxClientError("404NotFound", { consultedResource: "/getPotato", errorCode: "NOT_FOUND_404", detail: "Potato was not found" }, StatusOptions.Status404Opt("Potato n4355"))

// Output
{
  httpStatus: 404,
  serverMessage: 'Not Found',
  consultedResource: '/getPotato',
  errorCode: "NOT_FOUND_404",
  errorDetails: { notFoundResource: 'Potato n4355' },
  error: true,
  success: false
}
Status options:
Method Params Description
Status404Opt
  • notFoundResource: string
Status405Opt
  • allowedMethods: string[]
Status406Opt
  • allowedRepresentations: string[]
Status407Opt
  • authenticationType: string
  • realm: string
Status408Opt
  • timeWaiting: string
Status409Opt
  • conflictResource: string
  • conflictId: string
Status410Opt
  • goneResource: string
  • reason: string
Status411Opt - Adds the field 'requiredHeader': 'Content-Length'
Status413Opt
  • maxAllowedSize: string
Status414Opt
  • maxAllowedLength: string
Status415Opt
  • supportedMediaTypes: string[]
Status416Opt
  • requestedContentRange: string
  • supportedContentRange: string
Status423Opt
  • lockedResource: string
Status424Opt
  • failedDependency: string
Response5xxServerError()
Params:
Name Type Attribute Description
statusCode StatusCode5xx
  • Mandatory
Status code of your response.
Supported:
  • "500InternalServerError": 500
  • "501NotImplemented": 501
  • "502BadGateway": 502
  • "503ServiceUnavailable": 503
  • "504GatewayTimeout": 504
  • "505HTTPVersionNotSupported": 505
  • "506VariantAlsoNegotiates": 506
  • "507InsufficientStorage": 507
  • "508LoopDetected": 508
  • "509BandwidthLimitExceeded": 509
  • "510NotExtended": 510
  • "511NetworkAuthenticationRequired": 511
  • "521ConnectionTimedOut": 521
input BaseErrorInput
  • Optional
Base error input object
input.consultedResource string
  • Optional
URL or name of the consulted resource
input.detail string
  • Optional
Detail of the response
input.serverMessage string
  • Optional
  • Default
Message that the server will send to the client
input.errorCode string
  • Optional
Error identifier code
input.errorDescription string
  • Optional
Error description
input.errorName string
  • Optional
Error name
input.errors any
  • Optional
Arbitrary errors you can add to your response
Example:

Output includes success and error fields by default.

Response5xxServerError("500InternalServerError", { consultedResource: "/getPotato", errorCode: "500SERVERERROR", errorName: "INTERNAL_SERVER_ERROR" })

// Output
{
  httpStatus: 500,
  serverMessage: 'Internal Server Error',
  consultedResource: '/getPotato',
  errorCode: '500SERVERERROR',
  errorName: 'INTERNAL_SERVER_ERROR',
  error: true,
  success: false
}

Default Responses

100s
// Status100Continue
{
  httpStatus: 100,
  serverMessage: "Continue",
  detail:
    "Continue with the request",
}

// Status101SwitchingProtocols
{
  httpStatus: 101,
  serverMessage: "Switching Protocols",
}

// Status102Processing
{
  httpStatus: 102,
  serverMessage: "Processing",
}

// Status103EarlyHints
{
  httpStatus: 103,
  serverMessage: "Checkpoint",
}
200s

  // Status200OK
  {
    httpStatus: 200,
    serverMessage: "OK",
    detail: "The request has been successfully processed"
  }

  // Status201Created
  {
    httpStatus: 201,
    serverMessage: "Created",
    detail: "Resource successfully created"
  }

  // Status202Accepted
  {
    httpStatus: 202,
    serverMessage: "Accepted",
    detail: "The request has been accepted for processing"
  }

  // Status203NonAuthoritativeInformation
  {
    httpStatus: 203,
    serverMessage: "Non-Authoritative Information",
    detail: "Non-Authoritative Information returned"
  }

  // Status204NoContent
  {
    httpStatus: 204
  }

  // Status205ResetContent
  {
    httpStatus: 205,
    serverMessage: "Reset Content",
    detail: "The request has been successfully processed, but no content is returned"
  }

  // Status206PartialContent
  {
    httpStatus: 206,
    serverMessage: "Partial Content",
    detail: "Partial Content returned"
  }

  // Status207MultiStatus
  {
    httpStatus: 207,
    serverMessage: "Multi-Status",
    detail: "Multi-Status returned"
  }

  // Status208AlreadyReported
  {
    httpStatus: 208,
    serverMessage: "Already Reported",
    detail: "Resource already reported"
  }

  // Status226IMUsed
  {
    httpStatus: 226,
    serverMessage: "IM Used",
    detail: "IM Used"
  }
300s

  // Status300MultipleChoices
  {
    httpStatus: 300,
    serverMessage: "Multiple Choices",
  }

  // Status301MovedPermanently
  {
    httpStatus: 301,
    serverMessage: "Moved Permanently",
  }

  // Status302Found
  {
    httpStatus: 302,
    serverMessage: "Found",
  }

  // Status303SeeOther
  {
    httpStatus: 303,
    serverMessage: "See Other",
  }

  // Status304NotModified
  {
    httpStatus: 304,
    serverMessage: "Not Modified",
  }

  // Status305UseProxy
  {
    httpStatus: 305,
    serverMessage: "Use Proxy",
  }

  // Status307TemporaryRedirect
  {
    httpStatus: 307,
    serverMessage: "Temporary Redirect",
  }

  // Status308PermanentRedirect
  {
    httpStatus: 308,
    serverMessage: "Permanent Redirect",
  }
400s

  // Status400BadRequest
  {
    httpStatus: 400,
    serverMessage: "Bad Request",
  }

  // Status401Unauthorized
  {
    httpStatus: 401,
    serverMessage: "Unauthorized",
  }

  // Status402PaymentRequired
  {
    httpStatus: 402,
    serverMessage: "Payment Required",
  }

  // Status403Forbidden
  {
    httpStatus: 403,
    serverMessage: "Forbidden",
  }

  // Status404NotFound
  {
    httpStatus: 404,
    serverMessage: "Not Found",
  }

  // Status405MethodNotAllowed
  {
    httpStatus: 405,
    serverMessage: "Method Not Allowed",
  }

  // Status406NotAcceptable
  {
    httpStatus: 406,
    serverMessage: "Not Acceptable",
  }

  // Status407ProxyAuthenticationRequired
  {
    httpStatus: 407,
    serverMessage: "Proxy Authentication Required",
  }

  // Status408RequestTimeout
  {
    httpStatus: 408,
    serverMessage: "Request Timeout",
  }

  // Status409Conflict
  {
    httpStatus: 409,
    serverMessage: "Conflict",
  }

  // Status410Gone
  {
    httpStatus: 410,
    serverMessage: "Gone",
  }

  // Status411LengthRequired
  {
    httpStatus: 411,
    serverMessage: "Length Required",
  }

  // Status412PreconditionFailed
  {
    httpStatus: 412,
    serverMessage: "Precondition Failed",
  }

  // Status413PayloadTooLarge
  {
    httpStatus: 413,
    serverMessage: "Payload Too Large",
  }

  // Status414URITooLong
  {
    httpStatus: 414,
    serverMessage: "URI Too Long",
  }
  
  // Status415UnsupportedMediaType
  {
    httpStatus: 415,
    serverMessage: "Unsupported Media Type",
  }

  // Status416RangeNotSatisfiable
  {
    httpStatus: 416,
    serverMessage: "Range Not Satisfiable",
  }

  // Status417ExpectationFailed
  {
    httpStatus: 417,
    serverMessage: "Expectation Failed",
  }

  // Status418ImATeapot
  {
    httpStatus: 418,
    serverMessage: "I'm a teapot",
  }

  // Status421MisdirectedRequest
  {
    httpStatus: 421,
    serverMessage: "Misdirected Request",
  }

  // Status422UnprocessableEntity
  {
    httpStatus: 422,
    serverMessage: "Unprocessable Entity",
  }

  // Status423Locked
  {
    httpStatus: 423,
    serverMessage: "Locked",
  }

  // Status424FailedDependency
  {
    httpStatus: 424,
    serverMessage: "Failed Dependency",
  }

  // Status425Unnassigned
  {
    httpStatus: 425,
    serverMessage: "Unassigned",
  }

  // Status426UpgradeRequired
  {
    httpStatus: 426,
    serverMessage: "Upgrade Required",
  }

  // Status428PreconditionRequired
  {
    httpStatus: 428,
    serverMessage: "Precondition Required",
  }

  // Status429TooManyRequests
  {
    httpStatus: 429,
    serverMessage: "Too Many Requests",
    // Details: "Too Many Requests"
  }

  // Status431RequestHeaderFieldsTooLarge
  {
    httpStatus: 431,
    serverMessage: "Request Header Fields Too Large",
  }

  // Status451UnavailableForLegalReasons
  {
    httpStatus: 451,
    serverMessage: "Unavailable For Legal Reasons",
  }
500s
  // Status500InternalServerError
  {
    httpStatus: 500,
    serverMessage: "Internal Server Error",
  }

  // Status501NotImplemented
  {
    httpStatus: 501,
    serverMessage: "Not Implemented",
  }

  // Status502BadGateway
  {
    httpStatus: 502,
    serverMessage: "Bad Gateway",
  }

  // Status503ServiceUnavailable
  {
    httpStatus: 503,
    serverMessage: "Service Unavailable",
  }

  // Status504GatewayTimeout
  {
    httpStatus: 504,
    serverMessage: "Gateway Timeout",
  }

  // Status505HTTPVersionNotSupported
  {
    httpStatus: 505,
    serverMessage: "HTTP Version Not Supported",
  }

  // Status506VariantAlsoNegotiates
  {
    httpStatus: 506,
    serverMessage: "Variant Also Negotiates",
  }

  // Status507InsufficientStorage
  {
    httpStatus: 507,
    serverMessage: "Insufficient Storage",
  }

  // Status508LoopDetected
  {
    httpStatus: 508,
    serverMessage: "Loop Detected",
  }

  // Status509BandwithLimitExceeded
  {
    httpStatus: 509,
    serverMessage: "Bandwith Limit Exceeded",
  }

  // Status510NotExtended
  {
    httpStatus: 510,
    serverMessage: "Not Extended",
  }

  // Status511NetworkAuthenticationRequired
  {
    httpStatus: 511,
    serverMessage: "Network Authentication Required",
  }

  // Status521WebServerIsDown
  {
    httpStatus: 521,
    serverMessage: "Web Server Is Down",
  }