Skip to content

Instantly share code, notes, and snippets.

@toddnestor
Created April 3, 2025 03:32
Show Gist options
  • Save toddnestor/f367a8582098c24d9e03652c8aabfa24 to your computer and use it in GitHub Desktop.
Save toddnestor/f367a8582098c24d9e03652c8aabfa24 to your computer and use it in GitHub Desktop.
Resource
import {fetchAuthSession} from '@aws-amplify/auth';
const baseUrl = 'http://localhost:3000'; // process?.env?.REACT_APP_API_DOMAIN || '';
// makes a get request, called index because it typically is used to retrieve a collection
// of models, like index of the products for a search
export const index = <DataType = {}>(path: string) => {
return request<DataType[]>({
url: path,
method: 'GET',
});
};
// makes a get request for a single item
export const show = <DataType = {}>(path: string, id: string | number) => {
return request<DataType>({
url: `${path}/${id}`,
method: 'GET',
});
};
export const create = <DataType = {}>(path: string, data: Partial<DataType>) => {
return request<DataType, Partial<DataType>>({
url: path,
method: 'post',
data
});
};
export const update = <DataType = {}>(path: string, id: string | number, data: Partial<DataType>) => {
return request<DataType, Partial<DataType>>({
url: `${path}/${id}`,
method: 'PUT',
data
});
};
export const destroy = (path: string, id: string | number) => {
return request<void>({
url: `${path}/${id}`,
method: 'DELETE',
});
};
// create a resource and avoid repeating the path in index of the api calls
export const resource = <DataType = {}>(path: string) => {
path = `${baseUrl}${path}`;
return {
index: () => index<DataType>(path),
show: (id: string | number) => show<DataType>(path, id),
create: (data: Partial<DataType>) => create<DataType>(path, data),
update: (id: string | number, data: Partial<DataType>) => update<DataType>(path, id, data),
destroy: (id: string | number) => destroy(path, id),
};
};
interface RequestParams<DataType = {}> {
url: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'get' | 'post' | 'put' | 'delete' | 'patch';
headers?: Record<string, string>;
data?: DataType;
}
export const request = async <ReturnType, DataType = {}>({ url, method, headers, data }: RequestParams<DataType>): Promise<ReturnType> => {
const session = await fetchAuthSession();
const token = session?.tokens?.accessToken;
const cognitoId = session.userSub;
const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'AWS_COGNITO_ID': cognitoId || '',
...headers,
},
body: JSON.stringify(data),
});
return response.json() as unknown as Promise<ReturnType>;
};
const exports = {
request,
index,
create,
destroy,
show,
resource,
update
};
export default exports;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment