http-messenger

Messenger for sending HTTP requests from Node.js and browser.

Usage no npm install needed!

<script type="module">
  import httpMessenger from 'https://cdn.skypack.dev/http-messenger';
</script>

README

http-messenger

NPM version Total downloads

Messenger for sending HTTP requests from Node.js and browser. An easy way to request web servers. Example:

////////////////
// JavaScript //
////////////////

//(1) create messenger
http = new HttpMessenger({domain: "http://localhost:8080", path: "/backend"}).endpoint();

//(2) send PATCH request
resp = await(http("/auth/user/&user/state").patch({user: "me"}, {state: "LOCKED", obs: "Max failed attempts reached."}));

if (resp.status() == 200) {
  console.log("User state set.");
} else {
  console.log(util.format("200 expected: received: %s.", resp.text()));
}

#########
# Dogma #
#########

#(1) create messenger
http = HttpMessenger({domain="http://localhost:8080", path="/endpoint"}).endpoint()

#(2) send PATCH request
resp = await(http("/auth/user/&user/state").patch({user="me"}, {state="LOCKED", obs="Max failed attempts reached."}))

if resp.status() == 200 then
  print("User state set.")
else
  printf("200 expected; received: %s.", resp.text())

Developed in Dogma, compiled to JavaScript.

Engineered in Valencia, Spain, EU by EthronLabs.

Use

//JavaScript
const HttpMessenger = require("http-messenger");

#Dogma
use "http-messenger" as HttpMessenger

Messenger

A HTTP messenger is an object to send HTTP requests:

//JavaScript
constructor(props:object={})

#Dogma
constructor(props:={})
  • props: The messenger properties:
    • domain (string). Prefix to use as, for example, http://localhost:8080. In the browser, when not set, the current domain is used.
    • path (string). Path prefix to add when domain not specified explicitly in the endpoint. Example: /backend.
    • headers (object). Default HTTP headers to add to the requests.
    • cookies (object). Default cookies to add to the requests.
    • search (object). Default search parameters to add to the requests.

Example:

//JavaScript
msgr = new HttpMessenger({domain: "http://localhost:8080", path: "/backend", cookies: {Session=123}});

#Dogma
msgr = HttpMessenger({domain="http://localhost:8080", path="/backend", cookies={Session=123}})

Headers

The HTTP messenger instances have the headers field containing the default headers. This field contains the following members:

////////////////
// JavaScript //
////////////////

//return the header names.
headers.names : string[]

//return a header value.
headers.get(name:string)

//set a header value.
headers.set(name:string, value)

//remove a header.
headers.remove(name:string)

#########
# Dogma #
#########

#return the header names.
fn headers.name() : list

#return a header value.
fn headers.get(name:text)

#set a header value.
fn headers.set(name:text, value)

#remove a header.
fn headers.remove(name:text)

Example:

msgr.headers.set("Authorization", "eyJhbGciOiJIU...a0TXWcHg")

Cookies

The HTTP messenger instances have the cookies field containing the default cookies. This field contains the following members:

////////////////
// JavaScript //
////////////////

//return the cookie names.
cookies.names : string[]

//return a cookie value.
cookies.get(name:string)

//set a cookie value.
cookies.set(name:string, value)

//remove a cookie.
cookies.remove(name:string)

#########
# Dogma #
#########

#return the cookie names.
fn cookies.names : list

#return a cookie value.
fn cookies.get(name:text)

#set a cookie value.
fn cookies.set(name:text, value)

##remove a cookie.
fn cookies.remove(name:text)

Example:

msgr.cookies.set("session", "sessionId")
msgr.cookies.remove("session")

Endpoint

An endpoint represents a resource to request. This must be created using the HttpMessenger.endpoint() method:

//JavaScript
endpoint(path:string) : Endpoint

#Dogma
fn HttpMessenger.endpoint(path:text) : Endpoint
  • path (string) is the resource path. When no domain is specified, the messenger's domain and path are used. When the path ends with ?, search parameters must be set when the request is sent.

Example:

//JavaScript
msgr = new HttpMessenger({domain: "http://localhost:8080"});
ep = msgr.endpoint("/user/me");

#Dogma
msgr = HttpMessenger({domain="http://localhost:8080"})
ep = msgr.endpoint("/user/me")

We have the following too:

//JavaScript
http = new HttpMessenger({domain: "http://localhost:8080"}).endpoint();
ep = http("/user/me");

#Dogma
http = HttpMessenger({domain="http://localhost:8080"}).endpoint()
ep = http("/user/me")

When the endpoint() method is called with no argument, a function is returned for creating the endpoint more easily. Other example:

////////////////
// JavaScript //
////////////////
http = new HttpMessenger({domain: "http://localhost:8080"}).endpoint();
resp = await(http("/catalog/product/123").get());
//instead of:
http = new HttpMessenger({domain: "http://localhost:8080"});
resp = await(http.endpoint("/catalog/product/123").get());

#########
# Dogma #
#########
http = HttpMessenger({domain="http://localhost:8080"}).endpoint()
resp = await(http("/catalog/product/123").get())
#instead of:
http = HttpMessenger({domain: "http://localhost:8080"})
resp = await(http.endpoint("/catalog/product/123").get())

Request methods

Once we have the endpoint, we can perform HTTP requests with the following methods:

////////////////
// JavaScript //
////////////////
async get()
async get(search:object)                   //when ? in endpoint
async get(opts:object)                     //when ? not in endpoint
async get(search:object, opts:object)

async head()
async head(search:object)                  //when ? in endpoint
async head(opts:object)                    //when ? not in endpoint
async head(search:object, opts:object)

async delete()
async delete(search?:object)                //when ? in endpoint
async delete(opts?:object)                  //when ? not in endpoint
async delete(search?:object, opts?:object)

async post()
async post(data:object, opts?:object)
async post(data:object, contentType:string, opts?:object)
async post(search:object, data?:object, opts?:object)

async put()
async put(data:object, opts?:object)
async put(data:object, contentType:string, opts?:object)
async put(search:object, data:object, opts?:object)

async patch()
async patch(data:object, opts?:object)
async patch(data:object, contentType:string, opts?:object)
async patch(search?:object, data:object, opts?:object)

#########
# Dogma #
#########
async fn Endpoint.get()
async fn Endpoint.get(search?:map)                #when ? in endpoint
async fn Endpoint.get(opts?:map)                  #when ? not in endpoint
async fn Endpoint.get(search:map, opts?:map)

async fn Endpoint.head()
async fn Endpoint.head(search?:map)               #when ? in endpoint
async fn Endpoint.head(opts?:map)                 #when ? not in endpoint
async fn Endpoint.head(search:map, opts?:map)

async fn Endpoint.delete()
async fn Endpoint.delete(search?:map)             #when ? in endpoint
async fn Endpoint.delete(opts?:map)               #when ? not in endpoint
async fn Endpoint.delete(search?:map, opts?:map)

async fn Endpoint.post()
async fn Endpoint.post(data:map, opts?:map)
async fn Endpoint.post(data:map, contentType:text, opts?:map)
async fn Endpoint.post(search:map, data?:map, opts?:map)

async fn Endpoint.put()
async fn Endpoint.put(data:map, opts?:map)
async fn Endpoint.put(data:map, contentType:text, opts?:map)
async fn Endpoint.put(search:map, data:map, opts?:map)

async fn Endpoint.patch()
async fn Endpoint.patch(data:map, opts?:map)
async fn Endpoint.patch(data:map, contentType:text, opts?:map)
async fn Endpoint.patch(search?:map, data:map, opts?:map)
  • search (object) contains the search parameters to append to the path for this request.
  • contentType (string) indicates the Content-Type. If not specified, if data is String, text/plain used; otherwise, application/json.
  • opts (object), the request options: header (object), HTTP headers to send.
  • data (object), the request content to attach.

Examples:

////////////////
// JavaScript //
////////////////
msgr = new HttpMessenger({domain: "http://localhost:8080"});

//without search
ep = msgr.endpoint("/user/me");

resp = await(ep.get());
resp = await(ep.post({user: "me", password: "mypass"}));

//with search
ep = msgr.endpoint("/user?");

resp = await(ep.get({name: "me"}));  ///user?name=me
resp = await(ep.post({name: "me"}, {password: "mypass", tags: ["tag1", "tag2"]}));

#########
# Dogma #
#########
msgr = HttpMessenger({domain="http://localhost:8080"})

#without search
ep = msgr.endpoint("/user/me")

resp = await(ep.get())
resp = await(ep.post({user="me", password="mypass"}))

#with search
ep = msgr.endpoint("/user?")

resp = await(ep.get({name="me"}))   #/user?name=me
resp = await(ep.post({name="me"}, {password="mypass", tags=["tag1", "tag2"]}))

Parameterized endpoints

A parameterized endpoint is an endpoint with parameters which values are set in every request. A parameter is represented as &name. Example:

ep = msgr.endpoint("/user/&user")

When a parameterized endpoint used, the request methods must receive the parameter values as first argument:

////////////////
// JavaScript //
////////////////
async get(params:object|array)
async get(params:object|array, search:object)                 //when ? in endpoint
async get(params:object|array, opts:object)                   //when ? not in endpoint
async get(params:object|array, search:object, opts:object)

async head(params:object|array)
async head(params:object|array, search:object)                //when ? in endpoint
async head(params:object|array, opts:object)                  //when ? not in endpoint
async head(params:object|array, search:object, opts:object)

async delete(params:object|array)
async delete(params:object|array, search:object)              //when ? in endpoint
async delete(params:object|array, opts:object)                //when ? not in endpoint
async delete(params:object|array, search:object, opts:object)

async post(params:object|array, data:object, opts?:object)
async post(params:object|array, data:object, contentType:string, opts?:object)
async post(params:object|array, search:object, data?:object, opts?:object)
async post(params:object|array, search:object, data?:object, contentType:string, opts?:object)

async put(params:object|array, data:object, opts?:object)
async put(params:object|array, data:object, contentType:string, opts?:object)
async put(params:object|array, search:object, data:object, opts?:object)
async put(params:object|array, search:object, data:object, contentType:string, opts?:object)

async patch(params:object|array, data:object, opts?:object)
async patch(params:object|array, data:object, contentType:string, opts?:object)
async patch(params:object|array, search?:object, data:object, opts?:object)
async patch(params:object|array, search?:object, data:object, contentType:string, opts?:object)

#########
# Dogma #
#########
async fn Endpoint.get(params:(map,list))
async fn Endpoint.get(params:(map,list), search:map)              #when ? in endpoint
async fn Endpoint.get(params:(map,list), opts:map)                #when ? not in endpoint
async fn Endpoint.get(params:(map,list), search:map, opts:map)

async fn Endpoint.head(params:(map,list))
async fn Endpoint.head(params:(map,list), search:map)             #when ? in endpoint
async fn Endpoint.head(params:(map,list), opts:map)               #when ? not in endpoint
async fn Endpoint.head(params:(map,list), search:map, opts:map)

async fn Endpoint.delete(params:(map,list))
async fn Endpoint.delete(params:(map,list), search:map)            #when ? in endpoint
async fn Endpoint.delete(params:(map,list), opts:map)              #when ? not in endpoint
async fn Endpoint.delete(params:(map,list), search:map, opts:map)

async fn Endpoint.post(params:(map,list), data:map, opts?:map)
async fn Endpoint.post(params:(map,list), data:map, contentType:text, opts?:map)
async fn Endpoint.post(params:(map,list), search:map, data?:map, opts?:map)
async fn Endpoint.post(params:(map,list), search:map, data?:map, contentType:text, opts?:map)

async fn Endpoint.put(params:(map,list), data:map, opts?:map)
async fn Endpoint.put(params:(map,list), data:map, contentType:text, opts?:map)
async fn Endpoint.put(params:(map,list), search:map, data:map, opts?:map)
async fn Endpoint.put(params:(map,list), search:map, data:map, contentType:text, opts?:map)

async fn Endpoint.patch(params:(map,list), data:map, opts?:map)
async fn Endpoint.patch(params:(map,list), data:map, contentType:text, opts?:map)
async fn Endpoint.patch(params:(map,list), search?:map, data:map, opts?:map)
async fn Endpoint.patch(params:(map,list), search?:map, data:map, contentType:text, opts?:map)

The parameters can be passed as object or array. When array, positional passing used; when object, name used.

Example:

////////////////
// JavaScript //
////////////////
ep = msgr.endpoint("/user/&user");

resp = await(ep.get({user: "me"}));
resp = await(ep.post({user: "me"}, {password: "mypass", tags: ["tag1", "tag2"]}));

resp = await(ep.get(["me"]));
resp = await(ep.post(["me"], {password: "mypass", tags: ["tag1", "tag2"]}));

#########
# Dogma #
#########
ep = msgr.endpoint("/user/&user")

resp = await(ep.get({user="me"}))
resp = await(ep.post({user="me"}, {password="mypass", tags=["tag1", "tag2"]}))

resp = await(ep.get(["me"]))
resp = await(ep.post(["me"], {password="mypass", tags=["tag1", "tag2"]}))

Response object

When the request is performed, a promise is returned. The resolve function is going to receive a response object:

  • status() : number, the status code.
  • success() : bool, is a 2XX status code?
  • contentType() : string or cType() : string, the Content-Type header.
  • headers : object, the HTTP headers:
    • get(name:string) : string returns the specified header.
  • cookies : object, the cookies:
    • get(name:string) : string returns the specified cookie.
  • content() : any and c() : any, the response content.
  • text() : string, the content as text when content type is text/* or application/javascript. If ArrayBuffer, then this is converted to string. If object, JSON.stringify() used. Otherwise, String() used.
  • html() : string, the content as HTML text.
  • json() : object, the content as object when content type is application/json.

Example:

////////////////
// JavaScript //
////////////////
resp = await(msgr.endpoint("/user").post({user: "me", password: "mypass", tags: ["tag1", "tag2"]}));
if (resp.status() == 201) {
  console.log("User created.");
} else {
  console.log("201 expected but not received.");
}

resp = await(msgr.endpoint("/user").get());
if (resp.status() == 200) {
  console.log(resp.json());
} else {
  console.log("200 expected but not received.");
}

#########
# Dogma #
#########
resp = await(msgr.endpoint("/user").post({user="me", password="mypass", tags=["tag1", "tag2"]}))
if resp.status() == 201 then
  print("User created.")
else
  print("201 expected but not received.")

resp = await(msgr.endpoint("/user").get())
if resp.status() == 200 then
  printf(resp.json())
else
  print("200 expected but not received.")