RingoJS

Module ringo/utils/http

Provides utility functions to work with HTTP requests and responses. Most methods are useful for low-level operations only. To develop a full-featured web application it’s recommended to use a dedicated web framework like stick.

Functions

Class Headers

Instance Methods

Class ResponseFilter

Instance Methods


BufferFactory (data, encoding)

A stream factory that stores file upload in a memory buffer. This function is not meant to be called directly but to be passed as streamFactory argument to parseFileUpload().

The buffer is stored in the value property of the parameter's data object.

Parameters

Object data
String encoding

Headers (headers)

Returns an object for use as a HTTP request header collection. The returned object provides methods for setting, getting, and deleting its properties in a case-insensitive and case-preserving way. Multiple headers with the same field name will be merged into a comma-separated string. Therefore the Set-Cookie header is not supported by this function.

This function can be used as mixin for an existing JavaScript object or as a constructor.

Parameters

Object headers

an existing JS object. If undefined, a new object is created


Headers.prototype. add (name, value)

Add a header with the given name and value.

Parameters

String name

the header name

String value

the header value


Headers.prototype. contains (name)

Queries whether a header with the given name is set

Parameters

String name

the header name

Returns

Boolean

true if a header with this name is set


Headers.prototype. get (name)

Get the value of the header with the given name

Parameters

String name

the header name

Returns

String

the header value


Headers.prototype. set (name, value)

Set the header with the given name to the given value.

Parameters

String name

the header name

String value

the header value


Headers.prototype. toString ()

Returns a string representation of the headers in MIME format.

Returns

String

a string representation of the headers


Headers.prototype. unset (name)

Unsets any header with the given name

Parameters

String name

the header name


ResponseFilter (body, filter)

A utility class for implementing JSGI response filters. Each part of the response is first passed to the filter function. If the filter function returns a value, that value is passed on to the JSGI response stream.

Parameters

Object body

a JSGI response body

Function filter

a filter function


ResponseFilter.prototype. forEach (fn)

forEach function called by the JSGI connector.

Parameters

Function fn

the response handler callback function


TempFileFactory (data, encoding)

A stream factory that stores file uploads in temporary files. This function is not meant to be called directly but to be passed as streamFactory argument to parseFileUpload().

The name of the temporary file is stored in the tempfile property of the parameter's data object.

Parameters

Object data
String encoding

canonicalRanges (ranges)

Creates the canonical form of a range array. Also checks if all ranges are valid, otherwise throws an exception.

Example

// returns [[0,100], [150, 200]]
canonicalRanges([[0,100], [150, 200]]);

// returns [[0,200]]
canonicalRanges([[0,100], [50, 200]]);

// returns [[0, 300]]
canonicalRanges([[0,200], [50, 200], [200, 250], [245, 300]]);

Parameters

Array ranges

array in the form [[startOffset, endOffset], ...]; offsets start at zero

Returns

Array

the input array in the canonical form without overlapping ranges


getMimeParameter (headerValue, paramName)

Get a parameter from a MIME header value. For example, calling this function with "Content-Type: text/plain; charset=UTF-8" and "charset" will return "UTF-8".

Parameters

String headerValue

a header value

String paramName

a MIME parameter name


isFileUpload (contentType)

Find out whether the content type denotes a format this module can parse.

Parameters

String contentType

a HTTP request Content-Type header

Returns

Boolean

true if the content type can be parsed as form data by this module


isUrlEncoded (contentType)

Find out whether the content type denotes a format this module can parse.

Parameters

String contentType

a HTTP request Content-Type header

Returns

Boolean

true if the content type can be parsed as form data by this module


mergeParameter (params, name, value)

Adds a value to a parameter object using a square bracket property syntax. For example, parameter foo[bar][][baz]=hello will result in object structure {foo: {bar: [{baz : "hello"}]}}.

Parameters

Object params

the top level parameter object

String name

the parameter name

String value

the parameter value


parseFileUpload (request, params, encoding, streamFactory)

Parses a multipart MIME input stream.

Parameters

Object request

the JSGI request object

Object params

the parameter object to parse into. If not defined a new object is created and returned.

String encoding

optional encoding to apply to non-file parameters. Defaults to "UTF-8".

Function streamFactory

factory function to create streams for mime parts

Returns

Object

an object containing arbitrary parameters as string or uploaded files as an object with the keys name, filename, contentType,value`.


parseParameters (input, params, encoding)

Parses a string or binary object representing a query string via an URL or post data into a JavaScript object structure using the specified encoding. It uses the "&" as separator between parameters and "=" for assignments.

Example

parseParameters("a=1&b=2&b=3&c");
// returns { a: "1", b: ["2","3"], c: ""}

parseParameters("a[]=1&a[]=2&a[]=3");
// returns { a: ["1", "2","3"]}

parseParameters("foo[bar][baz]=hello&foo[bar][boo]=world");
// returns {foo: {bar: {baz: "hello", boo: "world"}}}

Parameters

Binary|String input

a Binary object or string containing the URL-encoded parameters

Object params

optional parameter object to parse into. If undefined a new object is created and returned.

String encoding

a valid encoding name, defaults to UTF-8

Returns

Object

the parsed parameter object


parseRange (rangeStr, size)

Parses the HTTP header and returns a list of ranges to serve. Returns an array of range arrays, iff a valid byte range has been requested, null otherwise.

Example

// returns [[0,499]]
parseRange("bytes=0-499", 10000);

// returns [[500,999], [0,499]]
parseRange("bytes=500-999,0-499", 10000);

// returns [[9500,9999]]
parseRange("bytes=-500", 10000);

Parameters

String rangeStr

value of the Range header field

Number size

optional length of the requested data in bytes; -1 indicates an unknown size

Returns

Array

parsed ranges as array in the form [[startOffset, endOffset], ...], offsets start at zero; or null for invalid header values.


setCookie (key, value, days, options)

Creates value for the Set-Cookie header for creating a cookie with the given name, value, and attributes.

All arguments except for key and value are optional. The days argument specifies the number of days until the cookie expires. To delete a cookie immediately, set the days argument to 0. If days is undefined or negative, the cookie is set for the current browser session.

Example

setCookie("username", "michi");
setCookie("password", "strenggeheim", 10,
  {path: "/mypath", domain: ".mydomain.org"});

setCookie("foo", "bar", 10,
  { httpOnly: true, secure: true, sameSite: true });

setCookie("foo", "bar", 10,
  { httpOnly: true, secure: true, sameSite: "Lax" })

Parameters

String key

the cookie name

String value

the cookie value

Number|Date days

optional the number of days to keep the cookie, or a Date object with the exact expiry date. If this is undefined or -1, the cookie is set for the current session. If this is 0, the cookie will be deleted immediately.

Object options

optional options argument which may contain the following properties:

  • path - the path on which to set the cookie (defaults to /)
  • domain - the domain on which to set the cookie (defaults to current domain)
  • secure - to only use this cookie for secure connections
  • httpOnly - to make the cookie inaccessible to client side scripts
  • sameSite - first-party-only cookie; asserts browsers not to send cookies along with cross-site requests; default is strict enforcement, any other enforcement can be provided as string.

Returns

String

the Set-Cookie header value


urlEncode (object, separator, equals)

Serializes an object's properties into an URL-encoded query string. If a property contains an array as value, the array will be serialized.

Example

// "foo=bar%20baz"
http.urlEncode({ foo: "bar baz" });

// "foo=bar%20baz&foo=2&foo=3"
http.urlEncode({ foo: ["bar baz", 2, 3] });

// "foo%5Bbar%5D%5B%5D%5Bbaz%5D=hello"
http.urlEncode({foo: {bar: [{baz: "hello"}]}});

Parameters

Object object

an object

String separator

optional string delimiting key-value pairs in the URL, defaults to &

String equals

optional string delimiting a key from its value, defaults to =

Returns

String

a string containing the URL encoded properties of the object