diff --git a/package.json b/package.json index 64a352b..9daf6fb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@eyeseetea/d2-api", "description": "Typed wrapper over DHIS2 API", - "version": "1.8.0", + "version": "1.8.0-beta.4", "license": "GPL-3.0", "author": "EyeSeeTea team", "repository": { diff --git a/src/api/dataStore.ts b/src/api/dataStore.ts index caa3aaf..f05de19 100644 --- a/src/api/dataStore.ts +++ b/src/api/dataStore.ts @@ -1,6 +1,9 @@ -import { D2ApiResponse } from "./common"; +import { D2ApiResponse, HttpResponse } from "./common"; +import { HttpResponse as HttpClientResponse } from "../repositories/HttpClientRepository"; import { D2ApiGeneric } from "./d2Api"; +type UpdateResponse = HttpResponse; + export class DataStore { private endpoint: string; @@ -49,16 +52,19 @@ export class DataStore { const config = { url: `/${this.endpoint}/${namespace}/${key}`, data: value }; return d2Api - .request({ + .request({ method: "put", ...config, validateStatus: validate404, }) .flatMap(response => { if (response.status === 404) { - return d2Api.request({ method: "post", ...config }); + return d2Api + .request({ method: "post", ...config }) + .map(validateResponse); } else { - return D2ApiResponse.build({ response: Promise.resolve(response) }); + const voidResponse = { ...response, data: validateResponse(response) }; + return D2ApiResponse.build({ response: Promise.resolve(voidResponse) }); } }); } @@ -67,12 +73,12 @@ export class DataStore { const { d2Api, namespace } = this; return d2Api - .request({ + .request({ method: "delete", url: `/${this.endpoint}/${namespace}/${key}`, validateStatus: validate404, }) - .map(response => (response.status === 404 ? false : true)); + .map(response => (response.status === 404 ? false : response.data.status === "OK")); } } @@ -80,6 +86,15 @@ function validate404(status: number): boolean { return (status >= 200 && status < 300) || status === 404; } +function validateResponse(response: HttpClientResponse>): undefined { + const { data } = response; + if (response.status === 200 && data.status === "OK") { + return; + } else { + throw new Error(data.message || "Invalid response from server"); + } +} + export type DataStoreType = "global" | "user"; export interface DataStoreKeyMetadata {