Skip to content

Commit

Permalink
Merge pull request #93 from EyeSeeTea/features/check-update-data-store
Browse files Browse the repository at this point in the history
[data store] validate response of update operations
  • Loading branch information
adrianq authored Apr 12, 2021
2 parents 6c9fe0b + b0484dd commit 2d8c555
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
27 changes: 21 additions & 6 deletions src/api/dataStore.ts
Original file line number Diff line number Diff line change
@@ -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<undefined>;

export class DataStore {
private endpoint: string;

Expand Down Expand Up @@ -49,16 +52,19 @@ export class DataStore {
const config = { url: `/${this.endpoint}/${namespace}/${key}`, data: value };

return d2Api
.request<void>({
.request<UpdateResponse>({
method: "put",
...config,
validateStatus: validate404,
})
.flatMap(response => {
if (response.status === 404) {
return d2Api.request({ method: "post", ...config });
return d2Api
.request<UpdateResponse>({ 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) });
}
});
}
Expand All @@ -67,19 +73,28 @@ export class DataStore {
const { d2Api, namespace } = this;

return d2Api
.request({
.request<UpdateResponse>({
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"));
}
}

function validate404(status: number): boolean {
return (status >= 200 && status < 300) || status === 404;
}

function validateResponse(response: HttpClientResponse<HttpResponse<unknown>>): 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 {
Expand Down

0 comments on commit 2d8c555

Please sign in to comment.