motidata
Version:
Data retrieval library for services (e.g. App) accessing MotiMate's main Api
66 lines • 2.36 kB
JavaScript
import { ContentType, MimeTypes } from "../constants/ContentTypeHeader.js";
import { CustomHeadersNames } from "../constants/CustomHeaders.js";
export class BaseRepository {
apiBaseUrl;
publicApiKey;
sessionRepository;
static Api = { mockaroo: "https://my.api.mockaroo.com" };
static Routes = {
registration: "registration",
activation: "activation",
personalGoal: "personal-goal",
group: "group",
message: "group/message",
userInfo: "user-info",
};
constructor(apiBaseUrl, publicApiKey, sessionRepository) {
this.apiBaseUrl = apiBaseUrl;
this.publicApiKey = publicApiKey;
this.sessionRepository = sessionRepository;
}
/**
* @throws any {@link sessionRepository} related Error
*/
async buildBaseHeaders() {
const HEADERS = new Headers({
[CustomHeadersNames.sessionId]: await this.sessionRepository.readSessionId(),
[CustomHeadersNames.apiKey]: this.publicApiKey,
[ContentType]: MimeTypes.applicationJson,
});
return HEADERS;
}
/**
* Sets the Content-Type to application/json by default. Can be overridden by settin {@link extraHeaders}.
* @protected
* @throws any {@link sessionRepository} related Error
*/
async _bulildRequest({ route, method, queryParams = new URLSearchParams(), extraHeaders = new Headers(), body, signal, }) {
const headers = await this.buildBaseHeaders();
extraHeaders.forEach((headerValue, headerName) => {
headers.append(headerName, headerValue);
});
return new Request(`${this.apiBaseUrl}/${route}?${queryParams.toString()}`, {
method,
headers,
body,
signal: signal,
});
}
/**
* @protected
*/
async _buildJsonRequest(unserializedBody, requestParams) {
return this._bulildRequest({
...requestParams,
body: JSON.stringify(unserializedBody),
});
}
/**
* @protected
* @throws any {@link sessionRepository} related Error
*/
async _handleResponseAfterAuthentication(response) {
await this.sessionRepository.saveSessionId(response.headers.get(CustomHeadersNames.sessionId) ?? "");
}
}
//# sourceMappingURL=BaseRepository.js.map