HTTP Requests
HTTP requests are easy to do. You can create your own requests from within client/rest-client/rest-client.ts
. When you first open this file you should see that it's empty. So let's create a simple login request to get us started:
public async login(username: string, password: string): Promise<boolean> {
const requestBody: RequestBody = {
username: username,
password: password
};
const res: ApiResult<boolean> = await this._sendMessage<boolean>("login", HttpVerb.POST, null, requestBody);
return res.result;
}
The method above is fairly simple and all the magic happens within the _sendMessage
function:
_sendMessage<T>
: ApiResult
A function that makes a HTTP request.
Args
uri
(string): The uri to send the request to.method
(HttpVerb): The verb of the HTTP request. You can useHttpVerb
which includes constants for all verbs, e.g.HttpVerb.GET
,HttpVerb.POST
, etc.queryParams
(QueryParam[] - default:[]
): An array of objects representing query parameters. The object takes a property ofkey
andvalue
. Both are strings.requestBody
(RequestBody - default:{}
): An object where each property is the value of the body property.headers
(RequestHeaders - default:{}
): An object where each property is the value of a header, e.g.{ "Content-Type": "application/json" }
.addToQueue
(boolean - default:false
): Determines whether this request is added to themessageQueue
.
This function returns an ApiResult
object which encapsulates the result of the request. This looks like:
ApiResult<T> {
error: boolean;
errorMessage: string;
result: T;
}
If there is no error
on the ApiResult
then the request was successful and you can see the result of the request in the result
property.
Configure Your Endpoints
The RestClient
is expected to be configured before use. This is handled by your base appConfig
which is by default located in the root index.ts
file. You need to set this to pass in the base URI for your endpoint, e.g:
const appConfig: AppConfig = {
rest: {
baseUri: "https://my-api-endpoint-address.net/"
}
};
Each _sendMessage
call will append its uri
to this baseUri
that you specify.
Wrapping HTTP Requests
You can wrap your HTTP requests to handle errors, like so:
public async login(username: string, password: string): Promise<boolean> {
const requestBody: RequestBody = {
username: username,
password: password
};
try {
const res: ApiResult<boolean> = await this._sendMessage<boolean>("login", HttpVerb.POST, null, requestBody);
return res.result;
}
catch (ex) {
// Do something with the error
}
}
It's up to you if you wrap the request here, or you could wrap the login
method itself higher up in the chain (e.g. inside the manager
).