UNPKG

pocketbase-tools

Version:

451 lines (450 loc) 13.6 kB
import PocketBase from "pocketbase"; const __vite_import_meta_env__ = { "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SSR": false }; function getEnvVar(key, defaultValue) { if (typeof import.meta !== "undefined" && __vite_import_meta_env__?.[key]) { return __vite_import_meta_env__[key] || defaultValue; } if (typeof process !== "undefined" && process.env?.[key]) { return process.env[key] || defaultValue; } if (defaultValue !== void 0) return defaultValue; throw new Error(`[Config Error] 必需环境变量未配置: ${key}`); } function validateEnvVars(requiredVars) { requiredVars.forEach((key) => { try { getEnvVar(key); } catch (err) { console.warn(`[Env Warning] ${err.message}`); } }); } let globalInstance = null; let customInstance = null; function createPBClient(baseUrl) { return new PocketBase(baseUrl); } function initGlobalInstance() { const baseUrl = getEnvVar("VITE_POCKETBASE_URL", "http://localhost:8090"); globalInstance = createPBClient(baseUrl); return globalInstance; } function usePBClient(options) { if (options?.override) { if (options.instance) { customInstance = options.instance; return customInstance; } if (options.url) { customInstance = createPBClient(options.url); return customInstance; } resetPBInstances(); } if (options?.instance) { if (!customInstance || options.override !== false) { customInstance = options.instance; } return customInstance; } if (options?.url) { if (!customInstance || options.override !== false) { customInstance = createPBClient(options.url); } return customInstance; } if (customInstance) return customInstance; if (globalInstance) return globalInstance; return initGlobalInstance(); } function resetPBInstances() { globalInstance = null; customInstance = null; } const getCollect = (name) => usePBClient().collection(name); const filesCollect = getCollect("files"); const productCollect = getCollect("products"); const profileCollect = getCollect("profile"); const userCollect = getCollect("users"); const superusersCollect = getCollect("_superusers"); class Logger { constructor(enableConsole) { this.enableConsole = typeof enableConsole === "boolean" ? enableConsole : process.env.NODE_ENV !== "production"; } success(message, data) { if (this.enableConsole) { console.log(`✅ 成功: ${message}`, data ? JSON.stringify(data) : ""); } } error(message, error) { if (this.enableConsole) { console.error(`❌ 错误: ${message}`, error ? JSON.stringify(error) : ""); } } warn(message, data) { if (this.enableConsole) { console.warn(`⚠️ 警告: ${message}`, data ? JSON.stringify(data) : ""); } } info(message, data) { if (this.enableConsole) { console.info(`ℹ️ 信息: ${message}`, data ? JSON.stringify(data) : ""); } } } const logger = new Logger(); class ErrorHandler { handle(error) { const apiError = this.parseError(error); logger.error(apiError.message, apiError); } parseError(error) { if (error.response) { return { code: error.response.code || "UNKNOWN_ERROR", message: error.response.message || "未知错误", details: error.response.data }; } return { code: "UNKNOWN_ERROR", message: error.message || "发生未知错误", details: error }; } } const withErrorHandling = async (action, callback) => { try { const result = await callback(); logger.success(action, result); return result; } catch (error) { const message = error.response?.data?.message || error.message; logger.error(action, message); return null; } }; const getInstance = () => usePBClient(); const useFiles = { getTokenPayload: async () => { return await getInstance().files.getToken(); }, getAbsoluteURL: (record, fileFiled) => { return getInstance().files.getURL(record, fileFiled); } }; const AUTH_SUCCESS = "认证成功"; const LOGOUT_SUCCESS = "已登出"; const REFRESH_SUCCESS = "获取信息成功"; const VERIFY_EMAIL = "验证邮箱"; const logSuccess = (action, message, data) => logger.success(`${action} ${message}`, data); const getPBClient = (options) => usePBClient(options); const getCollectionName = (role) => role === "admin" ? "_superusers" : "users"; const getIdentifierField = (role) => role === "admin" ? "email" : "username"; const login = async (role, account, clientOptions) => { const { password } = account; if (!password) throw new Error("缺少密码"); const pb = getPBClient(clientOptions); const collectionName = getCollectionName(role); const identifierField = getIdentifierField(role); const identifier = account[identifierField]; if (!identifier) throw new Error(`缺少${identifierField === "email" ? "邮箱" : "用户名"}`); const authData = await pb.collection(collectionName).authWithPassword(identifier, password); logSuccess(role, AUTH_SUCCESS); return authData; }; const logout = () => { const pb = getPBClient(); if (pb.authStore.isValid) { pb.authStore.clear(); } logSuccess("", LOGOUT_SUCCESS); }; const refresh = async (role, clientOptions) => { const pb = getPBClient(clientOptions); const collectionName = getCollectionName(role); const data = await pb.collection(collectionName).authRefresh(); logSuccess(role, REFRESH_SUCCESS, data); return data; }; const verify = async (email) => { const result = await userCollect.requestVerification(email); logSuccess(email, VERIFY_EMAIL); return result; }; const useAuth = { login, logout, refresh, verify }; function toProduct(record) { return { id: record.id, title: record.title, desc: record.desc, img: record.img, video: record.video, addtime: record.addtime, created: record.created, updated: record.updated }; } async function addProduct(titleOrProduct, desc, img, video) { return withErrorHandling("添加产品", async () => { let productData; if (typeof titleOrProduct === "object") { productData = titleOrProduct; } else { productData = { title: titleOrProduct, desc: desc || "", img: img || "", video: video || "", addtime: (/* @__PURE__ */ new Date()).toISOString() }; } const result = await productCollect.create(productData); logger.success("添加产品成功", result); return toProduct(result); }); } async function updateProduct(id, updatedFields) { return withErrorHandling(`更新产品 (ID: ${id})`, async () => { const updatedRecord = await productCollect.update(id, updatedFields); logger.success(`产品更新成功: ${updatedRecord.title}`); return toProduct(updatedRecord); }); } async function createProductsCollection() { return withErrorHandling("创建 products 表", async () => { const collection = await productCollect.client.collections.create({ name: "products", type: "base", listRule: null, viewRule: null, createRule: "", updateRule: "", deleteRule: "", fields: [ { name: "title", type: "text", required: true }, { name: "desc", type: "text", required: false }, { name: "images", type: "file", required: false, maxSelect: 5, maxSize: 5 * 1024 * 1024, mimeTypes: [ "image/png", "image/jpeg", "image/gif", "image/webp", "application/octet-stream" ], protected: true }, { name: "video", type: "file", required: false, maxSelect: 1, maxSize: 100 * 1024 * 1024, mimeTypes: ["video/mp4", "video/gif"], protected: true }, { name: "addtime", type: "date", required: false } ] }); logger.success("products 表创建成功", collection); return collection; }); } async function deleteProduct(id) { return withErrorHandling(`删除产品 (ID: ${id})`, async () => { await productCollect.delete(id); logger.success(`产品删除成功: ${id}`); return true; }); } async function getAllProducts(options) { return withErrorHandling("获取所有产品列表", async () => { const records = await productCollect.getFullList({ filter: options?.filter, sort: options?.sort || void 0, expand: options?.expand?.join(",") }); logger.success(`成功获取到 ${records.length} 个产品`); return records.map(toProduct); }); } async function getProductById(id) { return withErrorHandling(`获取产品详情 (ID: ${id})`, async () => { const record = await productCollect.getOne(id); logger.success(`成功获取产品: ${record.title}`); return toProduct(record); }); } async function listAllCompanyProfiles() { return withErrorHandling("列出所有记录", async () => { return await profileCollect.getFullList(); }); } async function checkProfileCollectionExists() { return withErrorHandling("检查 profile 表是否存在", async () => { const pb = usePBClient(); const collections = await pb.collections.getFullList(); return !!collections.find((collection) => collection.name === "profile"); }); } async function createProfileCollection() { return withErrorHandling("创建 profile 表结构", async () => { const pb = usePBClient(); return await pb.collections.create({ name: "profile", type: "base", listRule: '@request.auth.id != ""', fields: [ { name: "companyName", type: "text", required: true }, { name: "contactEmail", type: "text", required: true }, { name: "contactPhone", type: "text", required: true }, { name: "companyAddress", type: "text", required: true }, { name: "allowRegistration", type: "bool", required: true } ] }); }); } function addCompanyProfile(companyNameOrProfile, contactEmail, contactPhone, companyAddress, allowRegistration) { return withErrorHandling("添加公司数据", async () => { let profile; if (typeof companyNameOrProfile === "object") { profile = companyNameOrProfile; } else { profile = { companyName: companyNameOrProfile, contactEmail, contactPhone, companyAddress, allowRegistration }; } return await profileCollect.create(profile); }); } async function updateCompanyProfile(recordId, updatedFields) { return withErrorHandling("更新记录", async () => { return await profileCollect.update(recordId, updatedFields); }); } async function deleteCompanyProfile(recordId) { return withErrorHandling("删除记录", async () => { return await profileCollect.delete(recordId); }); } function toUser(record) { return { collectionId: record.collectionId ?? void 0, collectionName: record.collectionName ?? void 0, id: record.id ?? void 0, email: record.email ?? "", name: record.name ?? void 0, emailVisibility: record.emailVisibility ?? void 0, avatar: record.avatar ?? void 0, verified: record.verified ?? void 0, created: record.created ?? void 0, updated: record.updated ?? void 0 }; } async function getAllUsers(options = {}) { return withErrorHandling("获取所有用户列表", async () => { const pb = usePBClient(); const userCollect2 = pb.collection("users"); const users = await userCollect2.getFullList({ filter: options.filter, sort: options.sort || "-created", expand: options.expand?.join(",") }); logger.success(`成功获取用户列表`, { total: users.length, filter: options.filter }); return users.map(toUser); }); } async function addUser(user) { return withErrorHandling("添加用户", async () => { const pb = usePBClient(); const userCollect2 = pb.collection("users"); const result = await userCollect2.create(user); logger.success("添加用户成功", result); return toUser(result); }); } async function updateUser(id, updatedFields) { return withErrorHandling("更新用户", async () => { const pb = usePBClient(); const userCollect2 = pb.collection("users"); const updated = await userCollect2.update(id, updatedFields); logger.success("用户更新成功", updated); return toUser(updated); }); } async function deleteUser(id) { return withErrorHandling("删除用户", async () => { const pb = usePBClient(); const userCollect2 = pb.collection("users"); const deleted = await userCollect2.delete(id); logger.success("用户删除成功", deleted); return !!deleted; }); } const index = usePBClient(); export { ErrorHandler, Logger, addCompanyProfile, addProduct, addUser, checkProfileCollectionExists, createProductsCollection, createProfileCollection, index as default, deleteCompanyProfile, deleteProduct, deleteUser, filesCollect, getAllProducts, getAllUsers, getCollect, getEnvVar, getProductById, listAllCompanyProfiles, logger, productCollect, profileCollect, resetPBInstances, superusersCollect, updateCompanyProfile, updateProduct, updateUser, useAuth, useFiles, usePBClient, userCollect, validateEnvVars, withErrorHandling }; //# sourceMappingURL=index.mjs.map