create API flow
This commit is contained in:
54
actions.ts
54
actions.ts
@ -1,31 +1,55 @@
|
||||
"use server";
|
||||
|
||||
import { APIResult, GCIAPIResult } from "./types";
|
||||
|
||||
const feelingFree = async (query: string): Promise<APIResult> => {
|
||||
console.log(query);
|
||||
const getRandomResultFromGCI = async (
|
||||
query: string,
|
||||
): Promise<APIResult<string>> => {
|
||||
try {
|
||||
if (!query) {
|
||||
return { error: true, errorMessage: "You must provide a search query." };
|
||||
}
|
||||
const response = await fetch(
|
||||
`https://guncadindex.com/api/releases/?${query}`,
|
||||
`https://guncadindex.com/api/releases/?query=${query}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
console.error(response.status);
|
||||
return { error: true, payload: "Something went wrong." };
|
||||
return { error: true, errorMessage: "Something went wrong." };
|
||||
}
|
||||
const { results }: GCIAPIResult = await response.json();
|
||||
const randomResult = results[Math.round(Math.random() * results.length)];
|
||||
const slug = randomResult.url.split("/").filter(Boolean).pop();
|
||||
if (!slug) {
|
||||
return { error: true, payload: "Could not retrieve results." };
|
||||
// handle no results found for dumb queries
|
||||
if (!results || results.length === 0) {
|
||||
return {
|
||||
error: false,
|
||||
payload: `https://guncadindex.com/search?query=${query}`,
|
||||
};
|
||||
}
|
||||
console.log(slug);
|
||||
return { payload: `https://guncadindex.com/detail/${slug}` };
|
||||
// select a random result from the API
|
||||
const randomResult = results[Math.floor(Math.random() * results.length)];
|
||||
const slug = randomResult.url.split("/").filter(Boolean).pop();
|
||||
// handle edge case
|
||||
if (!slug) {
|
||||
return { error: true, errorMessage: "Could not retrieve results." };
|
||||
}
|
||||
return { error: false, payload: `https://guncadindex.com/detail/${slug}` };
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
return { error: true, payload: error.message };
|
||||
console.error(error.message);
|
||||
}
|
||||
return { error: true, payload: "Something went wrong." };
|
||||
return { error: true, errorMessage: "Something went wrong." };
|
||||
}
|
||||
};
|
||||
|
||||
export { feelingFree };
|
||||
const lmgcitfy = async (query: string): Promise<APIResult<string>> => {
|
||||
if (!query) {
|
||||
return { error: true, errorMessage: "You must provide a search query." };
|
||||
}
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
searchParams.append("query", query);
|
||||
|
||||
const redirectURL = `https://guncadindex.com/search?${searchParams}`;
|
||||
|
||||
return { error: false, payload: redirectURL };
|
||||
};
|
||||
|
||||
export { getRandomResultFromGCI, lmgcitfy };
|
||||
|
||||
Reference in New Issue
Block a user