Skip to content

Commit

Permalink
[TM-1531] apiSlice add job resource
Browse files Browse the repository at this point in the history
  • Loading branch information
egrojMonroy committed Dec 12, 2024
1 parent aa5b7e6 commit 153050a
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 97 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"generate:api": "openapi-codegen gen api",
"generate:jobService": "openapi-codegen gen jobService",
"generate:userService": "openapi-codegen gen userService",
"generate:services": "npm run generate:userService",
"generate:services": "yarn generate:userService && yarn generate:jobService",
"tx:push": "eval $(grep '^TRANSIFEX_TOKEN' .env) && eval $(grep '^TRANSIFEX_SECRET' .env) && txjs-cli push --key-generator=hash src/ --token=$TRANSIFEX_TOKEN --secret=$TRANSIFEX_SECRET",
"tx:pull": "eval $(grep '^TRANSIFEX_TOKEN' .env) && eval $(grep '^TRANSIFEX_SECRET' .env) && txjs-cli pull --token=$TRANSIFEX_TOKEN --secret=$TRANSIFEX_SECRET"
},
Expand Down
100 changes: 5 additions & 95 deletions src/generated/v3/jobService/jobServiceFetcher.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,6 @@
export type JobServiceFetcherExtraProps = {
/**
* You can add some extra props to your generated fetchers.
*
* Note: You need to re-gen after adding the first property to
* have the `JobServiceFetcherExtraProps` injected in `JobServiceComponents.ts`
**/
};
// This type is imported in the auto generated `jobServiceComponents` file, so it needs to be
// exported from this file.
export type { ErrorWrapper } from "../utils";

const baseUrl = ""; // TODO add your baseUrl

export type ErrorWrapper<TError> = TError | { status: "unknown"; payload: string };

export type JobServiceFetcherOptions<TBody, THeaders, TQueryParams, TPathParams> = {
url: string;
method: string;
body?: TBody;
headers?: THeaders;
queryParams?: TQueryParams;
pathParams?: TPathParams;
signal?: AbortSignal;
} & JobServiceFetcherExtraProps;

export async function jobServiceFetch<
TData,
TError,
TBody extends {} | FormData | undefined | null,
THeaders extends {},
TQueryParams extends {},
TPathParams extends {}
>({
url,
method,
body,
headers,
pathParams,
queryParams,
signal
}: JobServiceFetcherOptions<TBody, THeaders, TQueryParams, TPathParams>): Promise<TData> {
try {
const requestHeaders: HeadersInit = {
"Content-Type": "application/json",
...headers
};

/**
* As the fetch API is being used, when multipart/form-data is specified
* the Content-Type header must be deleted so that the browser can set
* the correct boundary.
* https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#sending_files_using_a_formdata_object
*/
if (requestHeaders["Content-Type"].toLowerCase().includes("multipart/form-data")) {
delete requestHeaders["Content-Type"];
}

const response = await window.fetch(`${baseUrl}${resolveUrl(url, queryParams, pathParams)}`, {
signal,
method: method.toUpperCase(),
body: body ? (body instanceof FormData ? body : JSON.stringify(body)) : undefined,
headers: requestHeaders
});
if (!response.ok) {
let error: ErrorWrapper<TError>;
try {
error = await response.json();
} catch (e) {
error = {
status: "unknown" as const,
payload: e instanceof Error ? `Unexpected error (${e.message})` : "Unexpected error"
};
}

throw error;
}

if (response.headers.get("content-type")?.includes("json")) {
return await response.json();
} else {
// if it is not a json response, assume it is a blob and cast it to TData
return (await response.blob()) as unknown as TData;
}
} catch (e) {
let errorObject: Error = {
name: "unknown" as const,
message: e instanceof Error ? `Network error (${e.message})` : "Network error",
stack: e as string
};
throw errorObject;
}
}

const resolveUrl = (url: string, queryParams: Record<string, string> = {}, pathParams: Record<string, string> = {}) => {
let query = new URLSearchParams(queryParams).toString();
if (query) query = `?${query}`;
return url.replace(/\{\w*\}/g, key => pathParams[key.slice(1, -1)]) + query;
};
// The serviceFetch method is the shared fetch method for all service fetchers.
export { serviceFetch as jobServiceFetch } from "../utils";
4 changes: 3 additions & 1 deletion src/store/apiSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { HYDRATE } from "next-redux-wrapper";
import { Store } from "redux";

import { setAccessToken } from "@/admin/apiProvider/utils/token";
import { DelayedJobDto } from "@/generated/v3/jobService/jobServiceSchemas";
import { LoginDto, OrganisationDto, UserDto } from "@/generated/v3/userService/userServiceSchemas";

export type PendingErrorState = {
Expand Down Expand Up @@ -53,12 +54,13 @@ type StoreResourceMap<AttributeType> = Record<string, StoreResource<AttributeTyp

// The list of potential resource types. IMPORTANT: When a new resource type is integrated, it must
// be added to this list.
export const RESOURCES = ["logins", "organisations", "users"] as const;
export const RESOURCES = ["logins", "organisations", "users", "delayedJobs"] as const;

type ApiResources = {
logins: StoreResourceMap<LoginDto>;
organisations: StoreResourceMap<OrganisationDto>;
users: StoreResourceMap<UserDto>;
delayedJobs: StoreResourceMap<DelayedJobDto>;
};

export type JsonApiResource = {
Expand Down

0 comments on commit 153050a

Please sign in to comment.