Skip to content

Instantly share code, notes, and snippets.

@xXnikosXx
Created September 11, 2024 07:08
Show Gist options
  • Save xXnikosXx/30364370a8cf62a38b914b908ef748ee to your computer and use it in GitHub Desktop.
Save xXnikosXx/30364370a8cf62a38b914b908ef748ee to your computer and use it in GitHub Desktop.
// frontend/utils/fetch-api.ts
import { v4 as uuidv4 } from "uuid";
type StrapiFunctions = {
register: (
username: string,
email: string,
password: string,
) => Promise<void>;
getUserByEmail: (
email: string,
) => Promise<any>;
getUserById: (
id: string,
) => Promise<any>;
getVerificationTokenByEmail: (
email: string,
) => Promise<any>;
getVerificationTokenByToken: (
token: string,
) => Promise<any>;
generateVerificationToken: (
email: string,
) => Promise<any>;
deleteVerificationToken: (
id: number,
) => Promise<void>;
};
/**
* `strapi` is a Utility Module created to make fetching to and from the backend easier.
* Utilities: publicFetch(), fetch(), register(), login().
*
*/
const strapi: StrapiFunctions = {
/**
* Registers a new user with the backend by sending a POST request to the registration endpoint.
*
* @param {string} username - The desired username for the new user.
* @param {string} email - The email address of the new user.
* @param {string} password - The password for the new user account.
*
* @returns {Promise<void>} A promise that resolves when the registration request is completed.
* If the request fails or the response is not OK, it throws an error.
*
* @throws {Error} Throws an error if the registration request fails or the response is not OK.
*/
register: async (
username: string,
email: string,
password: string,
) => {
try{
const response = await fetch(`${process.env.STRAPI_URL}/api/auth/local/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
email,
password,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Something went wrong; response not OK. Check Strapi output.");
}
const jsonResponse = await response.json();
console.log("Success: ", jsonResponse);
}
catch (error) {
console.error("An error has occured: ", error);
};
},
/**
* Fetches a user with a specific email address.
*
* @param {string} email - The email address of the user.
*
* @returns {Promise<object>} - The user data if found, or null if not.
*/
getUserByEmail: async (email: string) => {
const url = `${process.env.STRAPI_URL}/api/users?filters[email][$eq]=${encodeURIComponent(email)}`;
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
});
if (!response.ok) {
console.log(`Failed to fetch user by email: ${response.statusText}`);
}
const user = await response.json();
return user;
}
catch {
return null;
}
},
/**
* Fetches a user with a specific ID.
*
* @param {string} id - The id of the user.
*
* @returns {Promise<object>} - The user data if found, or null if not.
*/
getUserById: async (id: string) => {
const url = `${process.env.STRAPI_URL}/api/users/${id}`;
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
});
if (!response.ok) {
console.log(`Failed to fetch user by email: ${response.statusText}`);
}
const user = await response.json();
return user;
}
catch {
return null;
}
},
getVerificationTokenByEmail: async (email: string) => {
const url = `${process.env.STRAPI_URL}/api/verification-tokens?filters[email][$eq]=${encodeURIComponent(email)}`;
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
});
const verificationToken = await response.json();
return verificationToken;
}
catch {
return null;
}
},
getVerificationTokenByToken: async (token: string) => {
const url = `${process.env.STRAPI_URL}/api/verification-tokens?filters[token][$eq]=${encodeURIComponent(token)}`;
try {
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
});
const verificationToken = await response.json();
return verificationToken;
}
catch {
return null;
}
},
generateVerificationToken: async (email: string) => {
const url = `${process.env.STRAPI_URL}/api/verification-tokens`;
const token = uuidv4();
const expires = new Date(new Date().getTime() + 3600 * 1000);
const existingToken = await strapi.getVerificationTokenByEmail(email);
console.log(existingToken);
if (existingToken.data[0]) {
await strapi.deleteVerificationToken(existingToken.data[0].id);
}
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
body: JSON.stringify({
data: {
email,
token,
expires,
}
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Response was not ok.");
}
const verificationToken = await response.json();
return verificationToken;
}
catch (error) {
console.log(error);
}
},
deleteVerificationToken: async (id: number) => {
const url = `${process.env.STRAPI_URL}/api/verification-tokens/${id}`;
try {
const response = await fetch(url, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.STRAPI_AUTH_TOKEN}`,
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Response was not ok.");
}
console.log("Token successfully deleted!")
}
catch (error) {
console.log(error);
}
},
}
export default strapi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment