Skip to content

Instantly share code, notes, and snippets.

@AleksejDix
Last active May 25, 2023 13:38
Show Gist options
  • Save AleksejDix/cb034fa3d99222b750b491846daf9f06 to your computer and use it in GitHub Desktop.
Save AleksejDix/cb034fa3d99222b750b491846daf9f06 to your computer and use it in GitHub Desktop.
import axios from 'redaxios';
import type { Response } from 'redaxios';
export const API = axios.create();
const request = <T, E>(request: Promise<Response<T>>) =>
request
.then(({ data }) => data)
.catch((error: E) => {
throw error;
});
export const index =
(path: string) =>
<Resource, Error>() =>
request<Resource[], Error>(API.get(`/${path}`));
export const create =
(path: string) =>
<Resource, Error>(item: Resource) =>
request<Resource, Error>(API.post(`/${path}`, item));
export const show =
(path: string) =>
<Resource, Error>(id: string) =>
request<Resource, Error>(API.get(`/${path}/${id}`));
export const update =
(path: string) =>
<Resource, Error>(id: string, item: Resource) =>
request<Resource, Error>(API.put(`/${path}/${id}`, item));
export const destroy =
(path: string) =>
<Resource, Error>(id: string) =>
request<Resource, Error>(API.delete(`/${path}/${id}`));
const defaultActions = {
index,
create,
show,
update,
destroy
};
type ActionKey = keyof typeof defaultActions;
type Actions = typeof defaultActions;
function createResource<T extends Actions, K extends ActionKey>(
path: string,
keys: K[]
): { [P in K]: ReturnType<T[P]> } {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const ret: any = {};
keys.forEach((key) => {
ret[key] = defaultActions[key](path);
});
return ret;
}
type Signature = {
id: string;
placement: {
x: number;
y: number;
};
};
type SignatureError = {
message: 'failed on my face';
};
// usage
const Signature = createResource('posts', ['create', 'index']);
Signature.create<Signature, SignatureError>({
id: 'some id ',
placement: {
x: 100,
y: 199
}
})
.then((data) => data)
.catch((error) => error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment