UNPKG

appwrite-utils-cli

Version:

Appwrite Utility Functions to help with database management, data conversion, data import, migrations, and much more. Meant to be used as a CLI tool, I do not recommend installing this in frontend environments.

127 lines (126 loc) 5.19 kB
import { AppwriteException, Client, } from "node-appwrite"; import fs from "node:fs"; import path from "node:path"; export const toPascalCase = (str) => { return (str // Split the string into words on spaces or camelCase transitions .split(/(?:\s+)|(?:([A-Z][a-z]+))/g) // Filter out empty strings that can appear due to the split regex .filter(Boolean) // Capitalize the first letter of each word and join them together .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .join("")); }; export const toCamelCase = (str) => { return str .replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => index === 0 ? word.toLowerCase() : word.toUpperCase()) .replace(/\s+/g, ""); }; export const ensureDirectoryExistence = (filePath) => { const dirname = path.dirname(filePath); if (fs.existsSync(dirname)) { return true; } ensureDirectoryExistence(dirname); fs.mkdirSync(dirname); }; export const writeFileSync = (filePath, content, options) => { ensureDirectoryExistence(filePath); fs.writeFileSync(filePath, content, options); }; export const readFileSync = (filePath) => { return fs.readFileSync(filePath, "utf8"); }; export const existsSync = (filePath) => { return fs.existsSync(filePath); }; export const mkdirSync = (filePath) => { ensureDirectoryExistence(filePath); fs.mkdirSync(filePath); }; export const readdirSync = (filePath) => { return fs.readdirSync(filePath); }; export const areCollectionNamesSame = (a, b) => { return (a.toLowerCase().trim().replace(" ", "") === b.toLowerCase().trim().replace(" ", "")); }; /** * Generates the view URL for a specific file based on the provided endpoint, project ID, bucket ID, file ID, and optional JWT token. * * @param {string} endpoint - the base URL endpoint * @param {string} projectId - the ID of the project * @param {string} bucketId - the ID of the bucket * @param {string} fileId - the ID of the file * @param {Models.Jwt} [jwt] - optional JWT token generated via the Appwrite SDK * @return {string} the generated view URL for the file */ export const getFileViewUrl = (endpoint, projectId, bucketId, fileId, jwt) => { return `${endpoint}/storage/buckets/${bucketId}/files/${fileId}/view?project=${projectId}${jwt ? `&jwt=${jwt.jwt}` : ""}`; }; /** * Generates a download URL for a file based on the provided endpoint, project ID, bucket ID, file ID, and optionally a JWT. * * @param {string} endpoint - The base URL endpoint. * @param {string} projectId - The ID of the project. * @param {string} bucketId - The ID of the bucket. * @param {string} fileId - The ID of the file. * @param {Models.Jwt} [jwt] - Optional JWT object for authentication with Appwrite. * @return {string} The complete download URL for the file. */ export const getFileDownloadUrl = (endpoint, projectId, bucketId, fileId, jwt) => { return `${endpoint}/storage/buckets/${bucketId}/files/${fileId}/download?project=${projectId}${jwt ? `&jwt=${jwt.jwt}` : ""}`; }; export const finalizeByAttributeMap = async (appwriteFolderPath, collection, item) => { const schemaFolderPath = path.join(appwriteFolderPath, "schemas"); const zodSchema = await import(`${schemaFolderPath}/${toCamelCase(collection.name)}.ts`); return zodSchema.parse({ ...item.context, ...item.finalData, }); }; export let numTimesFailedTotal = 0; /** * Tries to execute the given createFunction and retries up to 5 times if it fails. * * @param {() => Promise<any>} createFunction - The function to be executed. * @param {number} [attemptNum=0] - The number of attempts made so far (default: 0). * @return {Promise<any>} - A promise that resolves to the result of the createFunction or rejects with an error if it fails after 5 attempts. */ export const tryAwaitWithRetry = async (createFunction, attemptNum = 0, throwError = false) => { try { return await createFunction(); } catch (error) { if ((error instanceof AppwriteException && (error.message.toLowerCase().includes("fetch failed") || error.message.toLowerCase().includes("server error"))) || (error.code === 522 || error.code === "522")) { if (error.code === 522) { console.log("Cloudflare error. Retrying..."); } else { console.log(`Fetch failed on attempt ${attemptNum}. Retrying...`); } numTimesFailedTotal++; if (attemptNum > 5) { throw error; } await delay(2500); return tryAwaitWithRetry(createFunction, attemptNum + 1); } if (throwError) { throw error; } console.error("Error during retryAwait function: ", error); // @ts-ignore return Promise.resolve(); } }; export const getAppwriteClient = (endpoint, projectId, apiKey) => { return new Client() .setEndpoint(endpoint) .setProject(projectId) .setKey(apiKey); }; export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));