Package Exports
- servie
- servie/dist/body/browser
- servie/dist/body/browser/index.js
- servie/dist/body/node
- servie/dist/body/node/index.js
- servie/dist/body/universal
- servie/dist/headers
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (servie) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Standard, framework-agnostic HTTP interfaces for JavaScript servers and clients.
Installation
npm install servie --saveUsage
throwbackCompose middleware functions into a single functionservie-lambdaServie transport layer for AWS Lambdaservie-httpServie transport layer for node.js HTTPbusboyA streaming parser for HTML form dataqsandquerystringParse HTTP query string to objectget-bodyGeneral body parser for forms, JSON and textservie-corsCORS middleware for Servieservie-routeRouting middleware for Servieservie-mountMount Servie middleware on a path prefixservie-compat-httpMimic node.js HTTP using Servieservie-redirectCreate response objects for redirectionservie-cookie-storeAPI for managing client-side cookiesservie-errorhandlerStandard error handler for transport layersservie-finalhandlerStandard final handler for transport layershttp-errorsCreate HTTP errorsboomHTTP-friendly error objectsconsolidateTemplate rendering
Servie
Base HTTP class for common request and response logic.
import { Servie } from 'servie'Options
events?An instance ofEventEmitterheaders?An instance ofHeaderstrailer?An instance ofPromise<Headers>body?An instance ofBody
Properties
eventsAn event emitter for listening to the request and response lifecycleheadersThe headers as aHeadersinstancetrailerA promise that resolves to aHeadersinstancebodyThe request or response payloadstartedBoolean indicating if a request/response has startedfinishedBoolean indicating if a request/response has finishedbytesTransferredThe number of bytes sent in the HTTP request/responseallHeadersCombinedRequestandBodyheaders instance
Methods
clone()Abstract method implemented byRequestandResponseto clone the instance (throwsTypeErrorwhenstarted == true)
Events
startedwhenstarted == truefinishedwhenfinished == trueprogresswhenbytesTransferredincrementsconnectionwhenRequestconnection is availableabortwhenRequestis abortingabortedwhenRequesthas aborted successfully
Request
HTTP class for encapsulating a
Request, extendsServie.
import { Request } from 'servie'Options
const request = new Request({
url: '/',
method: 'GET'
})Extends
Servieoptions.
urlThe HTTP request url (string)method?The HTTP request method (string, default:GET)connection?Connection information ({ remoteAddress?: string, remotePort?: number, localAddress?: string, localPort?: number, encrypted?: boolean })
Properties
urlRequested url (string)methodRequested method (string)UrlRequest url parsed into individual parts (object)connectionHTTP connection information when available (object)
Methods
abort(): booleanAborts the HTTP connection
Events
abortRequest aborted and transport MUST handleerrorAn out-of-band error occurred and transport MUST handleresponseThe correspondingResponsehas startedconnectionEmitted when connection information becomes available
Response
HTTP class for encapsulating a
Response, extendsServie.
import { Response } from 'servie'Options
const response = new Response({})Extends
Servieoptions.
statusCode?The HTTP response status code (number)statusMessage?The HTTP response status message (string)
Properties
statusCodeThe HTTP response status code (number)statusMessage?The HTTP response status message (string)okReturns whether response was successful (status in range 200-299) (boolean)
Headers
Used by
ServieforRequest,ResponseandBodyobjects.
import { Headers, createHeaders } from 'servie'Options
const headers = createHeaders(...) // new Headers([...])Create Headers instance from raw value (e.g. HeadersObject | string[] | null).
Properties
rawHeadersThe raw HTTP headers list (string[])
Methods
set(name: string, value: string | string[]): thisSet a HTTP header by overriding case-insensitive headers of the same nameappend(name: string, value: string | string[]): thisAppend a HTTP headerget(name: string): string | undefinedRetrieve a case-insensitive HTTP headergetAll(name: string): string[]Retrieve a list of matching case-insensitive HTTP headershas(name: string): booleanCheck if a case-insensitive header is already setdelete(name: string): thisDelete a case-insensitive headerasObject(toLower?: boolean): HeadersObjectReturn the headers as a plain objectextend(obj: HeadersObject): thisExtends the current headers with an objectkeys()Iterable of the available header namesvalues()Iterable of header valuesentries()Iterable of headers as[key, value]clear()Clears the headers instanceclone()Clones theHeadersinstance
Static Methods
is(obj: any): booleanChecks if an object isHeaders
Body
Immutable representation of the body used by
RequestandResponse.
import { Body, createBody } from 'servie/dist/body/{node,browser,universal}'
Bodyis a complex part of Servie due to support for browsers and node.js together. TypeScript is also missing a good story for universal modules with code paths offering different features (e.g. streams in node.js, nativeReadableStreamin browsers), so it's required that you import a specific version for your environment.
Note: Each endpoint (body/node, body/browser, body/universal) offers the same basic API (Body, createBody). Universal relies on module bundlers (e.g. webpack) and package.json#browser to switch the node.js API with the browser API at bundle time. TypeScript will require dom types since the interface returns a union of possible bodies (node and browser).
Options
const body = createBody(...) // new Body({ rawBody: ... })Create a Body instance from raw data (e.g. Readable | ReadableStream | Buffer | ArrayBuffer | object | string | null).
Properties
bufferedIndicates the raw body is entirely in memory (boolean)bodyUsedIndicates the body has been read (boolean)hasBodyIndicates the body is not empty (boolean)headersInstance of body-related HTTP headers (Headers)
Methods
text(): Promise<string>Returns body as a UTF-8 stringjson(): Promise<any>Returns body parsed as JSONarrayBuffer(): Promise<ArrayBuffer>Returns the body as anArrayBufferinstancebuffer(): Promise<Buffer>Returns the body as aBufferinstance (node.js)stream(): ReadableReturns a readable node.js stream (node.js)readableStream(): ReadableStreamReturns a readable WHATWG stream (browsers)clone(): thisClones theBodyinstance (allowing body re-use, throwsTypeErrorwhenbodyUsed == true)
Static Methods
is(obj: any): booleanChecks if an object isBody
Implementers
If you're building the transports for Servie, there are some life cycle events you need to be aware of:
- Listen to the
errorevent onRequestandResponsefor errors - Listen to the
abortevent onRequestand destroy the HTTP request - Resolve
trailerpromise and append to HTTP request - Emit the
responseevent (withResponsearg) onRequestwhen server responds - Set
started = trueandfinished = trueonRequestandResponse(as appropriate) - Set
bytesTransferredonRequestandResponsewhen monitoring HTTP transfer progress
JavaScript
This module is designed for ES2015 environments and published with TypeScript definitions on NPM.
License
Apache 2.0