0.2.3 • Published 12 months ago

http-code-util v0.2.3

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

http-code-util

Constants enumerating the HTTP status codes.

All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), RFC2518 (WebDAV), RFC6585 (Additional HTTP Status Codes), and RFC7538 (Permanent Redirect) are supported.

Installation

npm install http-code-util --save

Usage (express 4.x)

import {
  ReasonPhrases,
  StatusCodes,
  getReasonPhrase,
  getStatusCode,
} from 'http-code-util';

response.status(StatusCodes.OK).send(ReasonPhrases.OK);

response.status(StatusCodes.INTERNAL_SERVER_ERROR).send({
  error: getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR),
});

response.status(getStatusCode('Internal Server Error')).send({
  error: 'Internal Server Error',
});

Codes

CodeConstantReason PhraseExplenation
100CONTINUEContinueThe server has received the request headers, and the client should proceed to send the request body.
101SWITCHING_PROTOCOLSSwitching ProtocolsThe requester has asked the server to switch protocols, and the server has agreed to do so.
102PROCESSINGProcessing(WebDAV) The server has received and is processing the request, but no response is available yet.
103EARLY_HINTSEarly HintsUsed to return some response headers before final HTTP message.
200OKOKThe request has succeeded.
201CREATEDCreatedThe request has been fulfilled, resulting in the creation of a new resource.
202ACCEPTEDAcceptedThe request has been accepted for processing, but the processing has not been completed.
203NON_AUTHORITATIVE_INFORMATIONNon-Authoritative InformationThe request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response.
204NO_CONTENTNo ContentThe server successfully processed the request, and is not returning any content.
205RESET_CONTENTReset ContentThe server successfully processed the request, asks that the requester reset its document view, and is not returning any content.
206PARTIAL_CONTENTPartial ContentThe server is delivering only part of the resource (byte serving) due to a range header sent by the client.
207MULTI_STATUSMulti-Status(WebDAV) The message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.
208ALREADY_REPORTEDAlready Reported(WebDAV) The members of a DAV binding have already been enumerated in a previous reply to this request, and are not being included again.
226IM_USEDIM UsedThe server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
300MULTIPLE_CHOICESMultiple ChoicesThe request has more than one possible response. The user-agent or user should choose one of them.
301MOVED_PERMANENTLYMoved PermanentlyThe URL of the requested resource has been changed permanently. The new URL is given in the response.
302FOUNDFoundThe URL of the requested resource has been changed temporarily. The new URL is given in the response.
303SEE_OTHERSee OtherThe response to the request can be found under another URL using a GET method.
304NOT_MODIFIEDNot ModifiedIndicates that the resource has not been modified since the version specified by the request headers.
305USE_PROXYUse ProxyThe requested resource is only available through a proxy, the address for which is provided in the response.
306SWITCH_PROXYSwitch ProxyNo longer used. Originally meant "Subsequent requests should use the specified proxy."
307TEMPORARY_REDIRECTTemporary RedirectThe URL of the requested resource has been changed temporarily. The new URL is given in the response. The request method should not be changed when reissuing the original request.
308PERMANENT_REDIRECTPermanent RedirectThe URL of the requested resource has been changed permanently. The new URL is given in the response. The request method should not be changed when reissuing the original request.
400BAD_REQUESTBad RequestThe server could not understand the request due to invalid syntax.
401UNAUTHORIZEDUnauthorizedThe client must authenticate itself to get the requested response.
402PAYMENT_REQUIREDPayment RequiredThis response code is reserved for future use.
403FORBIDDENForbiddenThe client does not have access rights to the content.
404NOT_FOUNDNot FoundThe server can not find the requested resource.
405METHOD_NOT_ALLOWEDMethod Not AllowedThe request method is known by the server but has been disabled and cannot be used.
406NOT_ACCEPTABLENot AcceptableThe server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers.
407PROXY_AUTHENTICATION_REQUIREDProxy Authentication RequiredThe client must first authenticate itself with the proxy.
408REQUEST_TIMEOUTRequest TimeoutThe server would like to shut down this unused connection.
409CONFLICTConflictThe request could not be completed due to a conflict with the current state of the target resource.
410GONEGoneThe content has been permanently deleted from server, with no forwarding address.
411LENGTH_REQUIREDLength RequiredThe server refuses to accept the request without a defined Content-Length header.
412PRECONDITION_FAILEDPrecondition FailedThe client has indicated preconditions in its headers which the server does not meet.
413PAYLOAD_TOO_LARGEPayload Too LargeRequest entity is larger than limits defined by server.
414URI_TOO_LONGURI Too LongThe URI requested by the client is longer than the server is willing to interpret.
415UNSUPPORTED_MEDIA_TYPEUnsupported Media TypeThe media format of the requested data is not supported by the server.
416RANGE_NOT_SATISFIABLERange Not SatisfiableThe range specified by the Range header field in the request can't be fulfilled.
417EXPECTATION_FAILEDExpectation FailedThe expectation indicated by the Expect request header field can't be met by the server.
418IM_A_TEAPOTI'm a teapotAny attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot".
421MISDIRECTED_REQUESTMisdirected RequestThe request was directed at a server that is not able to produce a response.
422UNPROCESSABLE_ENTITYUnprocessable Entity(WebDAV) The request was well-formed but was unable to be followed due to semantic errors.
423LOCKEDLocked(WebDAV) The resource that is being accessed is locked.
424FAILED_DEPENDENCYFailed Dependency(WebDAV) The request failed due to failure of a previous request.
425TOO_EARLYToo EarlyIndicates that the server is unwilling to risk processing a request that might be replayed.
426UPGRADE_REQUIREDUpgrade RequiredThe client should switch to a different protocol such as TLS/1.0.
428PRECONDITION_REQUIREDPrecondition RequiredThe origin server requires the request to be conditional.
429TOO_MANY_REQUESTSToo Many RequestsThe user has sent too many requests in a given amount of time ("rate limiting").
431REQUEST_HEADER_FIELDS_TOO_LARGERequest Header Fields Too LargeThe server is unwilling to process the request because its header fields are too large.
444CONNECTION_CLOSED_WITHOUT_RESPONSEConnection Closed Without ResponseThe server closed the connection without sending any response to the client.
449RETRY_WITHRetry WithThe server cannot honour the request because the user has not provided the required information.
450BLOCKED_BY_WINDOWS_PARENTAL_CONTROLSBlocked by Windows Parental ControlsThe request was blocked by Windows Parental Controls.
451UNAVAILABLE_FOR_LEGAL_REASONSUnavailable For Legal ReasonsThe user requests an illegal resource, such as a web page censored by a government.
499CLIENT_CLOSED_REQUESTClient Closed RequestThe client has closed the request before the server could send a response.
500INTERNAL_SERVER_ERRORInternal Server ErrorThe server has encountered a situation it doesn't know how to handle.
501NOT_IMPLEMENTEDNot ImplementedThe request method is not supported by the server and cannot be handled.
502BAD_GATEWAYBad GatewayThe server, while acting as a gateway or proxy, received an invalid response from the upstream server.
503SERVICE_UNAVAILABLEService UnavailableThe server is not ready to handle the request.
504GATEWAY_TIMEOUTGateway TimeoutThe server, while acting as a gateway or proxy, did not get a response in time from the upstream server.
505HTTP_VERSION_NOT_SUPPORTEDHTTP Version Not SupportedThe HTTP version used in the request is not supported by the server.
506VARIANT_ALSO_NEGOTIATESVariant Also NegotiatesThe server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
507INSUFFICIENT_STORAGEInsufficient Storage(WebDAV) The server is unable to store the representation needed to complete the request.
508LOOP_DETECTEDLoop Detected(WebDAV) The server detected an infinite loop while processing the request.
510NOT_EXTENDEDNot ExtendedFurther extensions to the request are required for the server to fulfill it.
511NETWORK_AUTHENTICATION_REQUIREDNetwork Authentication RequiredThe client needs to authenticate to gain network access.
599NETWORK_CONNECT_TIMEOUT_ERRORNetwork Connect Timeout ErrorThe network connection has timed out.

Additional Usage Examples

All constants can also be accessed directly

import { HTTP_200_CODE, HTTP_200_NAME } from 'http-code-util';

response.status(HTTP_200_CODE).send(HTTP_200_NAME);

Helper Functions

FunctionDescriptionAffects bundle size
getStatusCode(phrase)Returns the corresponding HTTP status code, or undefined if not found.🟡
getReasonphrase(code)Returns the corresponding HTTP status phrase, or undefined if not found.🟡
getDescription(code)Returns the corresponding HTTP status description, or undefined if not found.🔴
getStatusInfo(code)Returns an object o the corresponding HTTP status code, phrase and description, or undefined if not found.🔴
isSuccess(code)Returns true if the HTTP code is a success code (between 200 and 299).🟢
isRedirect(code)Returns true if the HTTP code is a redirect code (between 300 and 399).🟢
isInformational(code)Returns true if the HTTP code is an informational code (between 100 and 199).🟢
isClientError(code)Returns true if the HTTP code is a client error code (between 400 and 499).🟢
isServerError(code)Returns true if the HTTP code is a server error code (between 500 and 599).🟢
isOk(code)Returns true if the HTTP code is 200 (OK).🟢
isError(code)Returns true if the HTTP code is a client or server error code.🟢
hasContent(code)Returns true if the HTTP code has content (not 204, 205, 304, or an error).🟢
isInformationalOrSuccess(code)Returns true if the HTTP code is informational or a success code.🟢
isValid(code)Returns true if the HTTP code is a known HTTP code code.🟡

Treeshaking and bundlesize legend

ColorTreeshaking impactImpact on bundle size
🟢No or only specific code constants will get bundled.almost none
🟡All status codes and status phrases get bundled.small
🔴All status codes, status phrases and status descriptions get bundled.big

Usage Examples

import {
  isSuccess,
  isRedirect,
  isInformational,
  isClientError,
  isServerError,
  isOk,
  isError,
  hasContent,
  isInformationalOrSuccess,
  isValid,
} from 'http-code-util';

console.log(isSuccess(200)); // true
console.log(isRedirect(302)); // true
console.log(isInformational(100)); // true
console.log(isClientError(404)); // true
console.log(isServerError(500)); // true
console.log(isOk(200)); // true
console.log(isError(404)); // true
console.log(hasContent(200)); // true
console.log(isInformationalOrSuccess(200)); // true
console.log(isValid(200)); // true

License

This project is licensed under the MIT License - see the LICENSE file for details.

0.2.3

12 months ago

0.2.2

1 year ago

0.2.1-treecheck

1 year ago

0.2.1

1 year ago

0.1.0

1 year ago

0.0.1

1 year ago