Formatted all .ts files
This commit is contained in:
@@ -7,178 +7,170 @@ type MethodTypes = "get" | "delete" | "head" | "options";
|
||||
type MethodTypesWithBody = "post" | "put" | "patch";
|
||||
|
||||
const dataProvider = (
|
||||
apiUrl: string,
|
||||
httpClient: AxiosInstance = axiosInstance,
|
||||
): Omit<
|
||||
Required<DataProvider>,
|
||||
"createMany" | "updateMany" | "deleteMany"
|
||||
> => ({
|
||||
getList: async ({ resource, meta, pagination, sorters, filters }) => {
|
||||
const url = `${apiUrl}/${resource}`;
|
||||
apiUrl: string,
|
||||
httpClient: AxiosInstance = axiosInstance
|
||||
): Omit<Required<DataProvider>, "createMany" | "updateMany" | "deleteMany"> => ({
|
||||
getList: async ({ resource, meta, pagination, sorters, filters }) => {
|
||||
const url = `${apiUrl}/${resource}`;
|
||||
|
||||
const { headers: headersFromMeta, method } = meta ?? {};
|
||||
const queryParams: Record<string, string | number> = meta?.queryParams ?? {};
|
||||
const requestMethod = (method as MethodTypes) ?? "get";
|
||||
const { headers: headersFromMeta, method } = meta ?? {};
|
||||
const queryParams: Record<string, string | number> = meta?.queryParams ?? {};
|
||||
const requestMethod = (method as MethodTypes) ?? "get";
|
||||
|
||||
if (pagination && pagination.mode == "server") {
|
||||
const pageSize = pagination.pageSize ?? 10;
|
||||
const offset = ((pagination.current ?? 1) - 1) * pageSize;
|
||||
queryParams["limit"] = pageSize;
|
||||
queryParams["offset"] = offset;
|
||||
if (pagination && pagination.mode == "server") {
|
||||
const pageSize = pagination.pageSize ?? 10;
|
||||
const offset = ((pagination.current ?? 1) - 1) * pageSize;
|
||||
queryParams["limit"] = pageSize;
|
||||
queryParams["offset"] = offset;
|
||||
}
|
||||
|
||||
if (sorters && sorters.length > 0) {
|
||||
queryParams["sort"] = sorters
|
||||
.map((sort) => {
|
||||
const field = sort.field;
|
||||
return `${field}:${sort.order}`;
|
||||
})
|
||||
.join(",");
|
||||
}
|
||||
|
||||
if (filters && filters.length > 0) {
|
||||
filters.forEach((filter) => {
|
||||
if (!("field" in filter)) {
|
||||
throw Error("Filter must be a LogicalFilter.");
|
||||
}
|
||||
const field = filter.field;
|
||||
if (filter.value.length > 0) {
|
||||
const filterValueArray = Array.isArray(filter.value) ? filter.value : [filter.value];
|
||||
|
||||
if (sorters && sorters.length > 0) {
|
||||
queryParams["sort"] = sorters.map((sort) => {
|
||||
const field = sort.field
|
||||
return `${field}:${sort.order}`;
|
||||
}).join(",")
|
||||
const filterValue = filterValueArray
|
||||
.map((value) => {
|
||||
if (value === "<empty>") {
|
||||
return "";
|
||||
}
|
||||
return value;
|
||||
})
|
||||
.join(",");
|
||||
|
||||
queryParams[field] = filterValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (filters && filters.length > 0) {
|
||||
filters.forEach(filter => {
|
||||
if (!("field" in filter)) {
|
||||
throw Error("Filter must be a LogicalFilter.")
|
||||
}
|
||||
const field = filter.field
|
||||
if (filter.value.length > 0) {
|
||||
const filterValueArray = Array.isArray(filter.value) ? filter.value : [filter.value]
|
||||
const { data, headers } = await httpClient[requestMethod](`${url}`, {
|
||||
headers: headersFromMeta,
|
||||
params: queryParams,
|
||||
});
|
||||
|
||||
const filterValue = filterValueArray.map((value) => {
|
||||
if (value === "<empty>") {
|
||||
return ""
|
||||
}
|
||||
return value
|
||||
}).join(",")
|
||||
// console.log(url, requestMethod, queryParams, data, headers)
|
||||
|
||||
queryParams[field] = filterValue
|
||||
}
|
||||
});
|
||||
}
|
||||
return {
|
||||
data,
|
||||
total: parseInt(headers["x-total-count"]) ?? 100,
|
||||
};
|
||||
},
|
||||
|
||||
const { data, headers } = await httpClient[requestMethod](
|
||||
`${url}`,
|
||||
{
|
||||
headers: headersFromMeta,
|
||||
params: queryParams,
|
||||
},
|
||||
);
|
||||
getMany: async () => {
|
||||
throw new Error("getMany not implemented");
|
||||
},
|
||||
|
||||
// console.log(url, requestMethod, queryParams, data, headers)
|
||||
create: async ({ resource, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}`;
|
||||
|
||||
return {
|
||||
data,
|
||||
total: parseInt(headers["x-total-count"]) ?? 100,
|
||||
};
|
||||
},
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "post";
|
||||
|
||||
getMany: async () => {
|
||||
throw new Error("getMany not implemented");
|
||||
},
|
||||
const { data } = await httpClient[requestMethod](url, variables, {
|
||||
headers,
|
||||
});
|
||||
|
||||
create: async ({ resource, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}`;
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "post";
|
||||
update: async ({ resource, id, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, variables, {
|
||||
headers,
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "patch";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, variables, {
|
||||
headers,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
getOne: async ({ resource, id, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypes) ?? "get";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, { headers });
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
deleteOne: async ({ resource, id, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "delete";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, {
|
||||
data: variables,
|
||||
headers,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
getApiUrl: () => {
|
||||
return apiUrl;
|
||||
},
|
||||
|
||||
custom: async ({ url, method, payload, query, headers }) => {
|
||||
let requestUrl = `${url}?`;
|
||||
|
||||
if (query) {
|
||||
requestUrl = `${requestUrl}&${stringify(query)}`;
|
||||
}
|
||||
|
||||
if (headers) {
|
||||
httpClient.defaults.headers = {
|
||||
...httpClient.defaults.headers,
|
||||
...headers,
|
||||
};
|
||||
}
|
||||
|
||||
let axiosResponse;
|
||||
switch (method) {
|
||||
case "put":
|
||||
case "post":
|
||||
case "patch":
|
||||
axiosResponse = await httpClient[method](url, payload);
|
||||
break;
|
||||
case "delete":
|
||||
axiosResponse = await httpClient.delete(url, {
|
||||
data: payload,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
axiosResponse = await httpClient.get(requestUrl);
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
const { data } = axiosResponse;
|
||||
|
||||
update: async ({ resource, id, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "patch";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, variables, {
|
||||
headers,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
getOne: async ({ resource, id, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypes) ?? "get";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, { headers });
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
deleteOne: async ({ resource, id, variables, meta }) => {
|
||||
const url = `${apiUrl}/${resource}/${id}`;
|
||||
|
||||
const { headers, method } = meta ?? {};
|
||||
const requestMethod = (method as MethodTypesWithBody) ?? "delete";
|
||||
|
||||
const { data } = await httpClient[requestMethod](url, {
|
||||
data: variables,
|
||||
headers,
|
||||
});
|
||||
|
||||
return {
|
||||
data,
|
||||
};
|
||||
},
|
||||
|
||||
getApiUrl: () => {
|
||||
return apiUrl;
|
||||
},
|
||||
|
||||
custom: async ({
|
||||
url,
|
||||
method,
|
||||
payload,
|
||||
query,
|
||||
headers,
|
||||
}) => {
|
||||
let requestUrl = `${url}?`;
|
||||
|
||||
if (query) {
|
||||
requestUrl = `${requestUrl}&${stringify(query)}`;
|
||||
}
|
||||
|
||||
if (headers) {
|
||||
httpClient.defaults.headers = {
|
||||
...httpClient.defaults.headers,
|
||||
...headers,
|
||||
};
|
||||
}
|
||||
|
||||
let axiosResponse;
|
||||
switch (method) {
|
||||
case "put":
|
||||
case "post":
|
||||
case "patch":
|
||||
axiosResponse = await httpClient[method](url, payload);
|
||||
break;
|
||||
case "delete":
|
||||
axiosResponse = await httpClient.delete(url, {
|
||||
data: payload,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
axiosResponse = await httpClient.get(requestUrl);
|
||||
break;
|
||||
}
|
||||
|
||||
const { data } = axiosResponse;
|
||||
|
||||
return Promise.resolve({ data });
|
||||
},
|
||||
return Promise.resolve({ data });
|
||||
},
|
||||
});
|
||||
|
||||
export default dataProvider;
|
||||
|
||||
@@ -4,13 +4,13 @@ import { BaseKey, LiveEvent, LiveProvider } from "@refinedev/core";
|
||||
* A spoolman websocket event.
|
||||
*/
|
||||
interface Event {
|
||||
type: "updated" | "deleted" | "added";
|
||||
resource: "filament" | "spool" | "vendor";
|
||||
date: string;
|
||||
payload: {
|
||||
id: number;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
type: "updated" | "deleted" | "added";
|
||||
resource: "filament" | "spool" | "vendor";
|
||||
date: string;
|
||||
payload: {
|
||||
id: number;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -21,25 +21,24 @@ interface Event {
|
||||
* @returns The WebSocket URL
|
||||
*/
|
||||
function toWebsocketURL(apiUrl: string) {
|
||||
if (apiUrl[0] === "/") {
|
||||
// Relative URL, e.g. "/api/v1/..."
|
||||
if (apiUrl[0] === "/") {
|
||||
// Relative URL, e.g. "/api/v1/..."
|
||||
|
||||
// Get the current browser URL
|
||||
const currentURL = window.location.href;
|
||||
// Get the current browser URL
|
||||
const currentURL = window.location.href;
|
||||
|
||||
// Split the URL to separate the protocol, host, and path
|
||||
const urlParts = currentURL.split('/');
|
||||
const host = urlParts[2];
|
||||
// Split the URL to separate the protocol, host, and path
|
||||
const urlParts = currentURL.split("/");
|
||||
const host = urlParts[2];
|
||||
|
||||
// Create the WebSocket URL by adding "ws://" as the protocol and the relative URL as the path
|
||||
return `ws://${host}${apiUrl}`;
|
||||
}
|
||||
else {
|
||||
// Absolute URL, e.g. "https://example.com/api/v1/..."
|
||||
// Create the WebSocket URL by adding "ws://" as the protocol and the relative URL as the path
|
||||
return `ws://${host}${apiUrl}`;
|
||||
} else {
|
||||
// Absolute URL, e.g. "https://example.com/api/v1/..."
|
||||
|
||||
// Replace the protocol with "ws://"
|
||||
return apiUrl.replace(/^http/, 'ws');
|
||||
}
|
||||
// Replace the protocol with "ws://"
|
||||
return apiUrl.replace(/^http/, "ws");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,77 +50,72 @@ function toWebsocketURL(apiUrl: string) {
|
||||
* @param id Specific ID to subscribe to, if any. If not specified, subscribes to all IDs.
|
||||
* @returns A function to unsubscribe from the resource
|
||||
*/
|
||||
function subscribeSingle(apiUrl: string, channel: string, resource: string, callback: (event: LiveEvent) => void, id?: BaseKey) {
|
||||
// Verify that WebSockets are supported
|
||||
if (!('WebSocket' in window)) {
|
||||
console.warn("WebSockets are not supported in this browser. Live updates will not be available.");
|
||||
return () => { };
|
||||
}
|
||||
function subscribeSingle(
|
||||
apiUrl: string,
|
||||
channel: string,
|
||||
resource: string,
|
||||
callback: (event: LiveEvent) => void,
|
||||
id?: BaseKey
|
||||
) {
|
||||
// Verify that WebSockets are supported
|
||||
if (!("WebSocket" in window)) {
|
||||
console.warn("WebSockets are not supported in this browser. Live updates will not be available.");
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const websocketURL = id ? toWebsocketURL(`${apiUrl}/${resource}/${id}`) : toWebsocketURL(`${apiUrl}/${resource}`);
|
||||
const websocketURL = id ? toWebsocketURL(`${apiUrl}/${resource}/${id}`) : toWebsocketURL(`${apiUrl}/${resource}`);
|
||||
|
||||
const ws = new WebSocket(websocketURL);
|
||||
ws.onmessage = (message) => {
|
||||
const data: Event = JSON.parse(message.data);
|
||||
const type = data.type === "added" ? "created" : data.type;
|
||||
const date = new Date(data.date);
|
||||
const ws = new WebSocket(websocketURL);
|
||||
ws.onmessage = (message) => {
|
||||
const data: Event = JSON.parse(message.data);
|
||||
const type = data.type === "added" ? "created" : data.type;
|
||||
const date = new Date(data.date);
|
||||
|
||||
const liveEvent: LiveEvent = {
|
||||
channel: channel,
|
||||
type: type,
|
||||
payload: {
|
||||
data: data.payload,
|
||||
ids: [data.payload.id],
|
||||
},
|
||||
date: date,
|
||||
}
|
||||
|
||||
callback(liveEvent);
|
||||
const liveEvent: LiveEvent = {
|
||||
channel: channel,
|
||||
type: type,
|
||||
payload: {
|
||||
data: data.payload,
|
||||
ids: [data.payload.id],
|
||||
},
|
||||
date: date,
|
||||
};
|
||||
|
||||
return () => {
|
||||
ws.close();
|
||||
};
|
||||
callback(liveEvent);
|
||||
};
|
||||
|
||||
return () => {
|
||||
ws.close();
|
||||
};
|
||||
}
|
||||
|
||||
const liveProvider = (
|
||||
apiUrl: string,
|
||||
): LiveProvider => ({
|
||||
subscribe: ({ channel, params, callback }) => {
|
||||
const {
|
||||
resource,
|
||||
subscriptionType,
|
||||
id,
|
||||
ids,
|
||||
} = params ?? {};
|
||||
const liveProvider = (apiUrl: string): LiveProvider => ({
|
||||
subscribe: ({ channel, params, callback }) => {
|
||||
const { resource, subscriptionType, id, ids } = params ?? {};
|
||||
|
||||
if (!subscriptionType) {
|
||||
throw new Error(
|
||||
"[useSubscription]: `subscriptionType` is required in `params`",
|
||||
);
|
||||
}
|
||||
if (!subscriptionType) {
|
||||
throw new Error("[useSubscription]: `subscriptionType` is required in `params`");
|
||||
}
|
||||
|
||||
if (!resource) {
|
||||
throw new Error(
|
||||
"[useSubscription]: `resource` is required in `params`",
|
||||
);
|
||||
}
|
||||
if (!resource) {
|
||||
throw new Error("[useSubscription]: `resource` is required in `params`");
|
||||
}
|
||||
|
||||
let idList: BaseKey[];
|
||||
if (ids) idList = ids;
|
||||
else if (id) idList = [id];
|
||||
else {
|
||||
// No ID specified, subscribe to all IDs
|
||||
return [subscribeSingle(apiUrl, channel, resource, callback)]
|
||||
}
|
||||
let idList: BaseKey[];
|
||||
if (ids) idList = ids;
|
||||
else if (id) idList = [id];
|
||||
else {
|
||||
// No ID specified, subscribe to all IDs
|
||||
return [subscribeSingle(apiUrl, channel, resource, callback)];
|
||||
}
|
||||
|
||||
return idList.map((id) => {
|
||||
return subscribeSingle(apiUrl, channel, resource, callback, id);
|
||||
});
|
||||
},
|
||||
unsubscribe: (closers: (() => void)[]) => {
|
||||
closers.forEach((fn) => fn());
|
||||
},
|
||||
})
|
||||
return idList.map((id) => {
|
||||
return subscribeSingle(apiUrl, channel, resource, callback, id);
|
||||
});
|
||||
},
|
||||
unsubscribe: (closers: (() => void)[]) => {
|
||||
closers.forEach((fn) => fn());
|
||||
},
|
||||
});
|
||||
|
||||
export default liveProvider;
|
||||
|
||||
Reference in New Issue
Block a user