kia-ml
Version:
Kia
139 lines (116 loc) • 3.33 kB
JavaScript
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { create } from 'apisauce';
import { getGeneralApiProblem } from './api-problem';
import { DEFAULT_API_CONFIG } from './api-config';
import { paginatedRequestTransformer } from "../transformers/request-transformer";
import { paginationTransformer } from '../transformers/pagination-transformer';
/**
* Manages all requests to the API.
*/
export class Api {
/**
* The underlying apisauce instance which performs the requests.
*/
/**
* Configurable options.
*/
/**
* Creates the api.
*
* @param config The configuration to use.
*/
constructor(config = DEFAULT_API_CONFIG) {
_defineProperty(this, "apisauce", void 0);
_defineProperty(this, "config", void 0);
this.config = config;
}
/**
* Sets up the API. This will be called during the bootup
* sequence and will happen before the first React component
* is mounted.
*
* Be as quick as possible in here.
*/
setup(apiConfig) {
// construct the apisauce instance
this.apisauce = create({
baseURL: apiConfig.serverBaseUrl,
timeout: this.config.timeout,
headers: {
Accept: 'application/json',
jwt: apiConfig.jwt,
client: apiConfig.clientId,
clientUserId: apiConfig.clientUserId
}
});
}
async getRequests(userId, url) {
const endPoint = url || "api/client-user-request/" + userId;
const response = await this.apisauce.get(endPoint);
if (!response.ok) {
const problem = getGeneralApiProblem(response);
if (problem) return problem;
}
console.log(response);
return {
kind: "ok",
requests: paginatedRequestTransformer(response),
pagination: paginationTransformer(response)
};
}
/**
* Gets a list of users.
*/
async getUsers() {
// make the api call
const response = await this.apisauce.get(`/users`); // the typical ways to die when calling an api
if (!response.ok) {
const problem = getGeneralApiProblem(response);
if (problem) return problem;
}
const convertUser = raw => {
return {
id: raw.id,
name: raw.name
};
}; // transform the data into the format we are expecting
try {
const rawUsers = response.data;
const resultUsers = rawUsers.map(convertUser);
return {
kind: 'ok',
users: resultUsers
};
} catch {
return {
kind: 'bad-data'
};
}
}
/**
* Gets a single user by ID
*/
async getUser(id) {
// make the api call
const response = await this.apisauce.get(`/users/${id}`); // the typical ways to die when calling an api
if (!response.ok) {
const problem = getGeneralApiProblem(response);
if (problem) return problem;
} // transform the data into the format we are expecting
try {
const resultUser = {
id: response.data.id,
name: response.data.name
};
return {
kind: 'ok',
user: resultUser
};
} catch {
return {
kind: 'bad-data'
};
}
}
}
//# sourceMappingURL=api.js.map