UNPKG

next-dev

Version:

Tentu, berikut adalah markdown yang telah diperbaiki:

116 lines (115 loc) 5.58 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = __importDefault(require("path")); const readdirp_1 = __importDefault(require("readdirp")); const fs_1 = __importDefault(require("fs")); const lodash_1 = __importDefault(require("lodash")); const prettier = __importStar(require("prettier")); const dir = 'src/lib/'; // Fungsi utama untuk menghasilkan API const generateApi = async (argv) => { const name = "fetchApi"; // const apiDir = createApiDirectory(); let list = initializeApiList(); const listPath = await generateApiFunctions(list); list.push(generatePathsMethod(listPath)); const text = `export const ${name} = {\n${list.join(',\n')}\n};`; const formattedText = await prettier.format(text, { parser: "typescript" }); fs_1.default.writeFileSync(path_1.default.join(dir, `${name}.ts`), formattedText, 'utf8'); console.log(`Generated ${name} DONE`); }; // Membuat direktori API jika belum ada // const createApiDirectory = () => { // const apiDir = path.join(process.cwd(), 'src/lib/api'); // if (!fs.existsSync(apiDir)) { // fs.mkdirSync(apiDir, { recursive: true }); // console.log('Created src/lib/api directory'); // } // return apiDir; // }; // Inisialisasi list API dengan fungsi dasar const initializeApiList = () => [ "\nhost: ''\n", "init(host: string) {\nthis.host = host;\n}" ]; // Menghasilkan fungsi API berdasarkan file yang ditemukan const generateApiFunctions = async (list) => { const listPath = []; for await (const entry of (0, readdirp_1.default)(path_1.default.join(process.cwd(), 'src/app/api'), { fileFilter: '*.ts' })) { const key = lodash_1.default.camelCase(generateFunctionName(entry.path)); const value = path_1.default.relative(path_1.default.join(process.cwd(), 'src/app/api'), entry.fullPath).replace('.ts', ''); list.push(generateFunctionCode(entry.fullPath, entry.path)); listPath.push(`${key}: \`\${this.host}/api/${value.replace(/route/g, '')}\``); } return listPath; }; // Menghasilkan metode paths const generatePathsMethod = (listPath) => `paths() {\nreturn {\n${listPath.join(',\n')}\n}\n}`; // Menghasilkan nama fungsi dari path file const generateFunctionName = (filePath) => { let baseFunctionName = filePath.replace('/route.ts', '').replace(/[^\w\s]/g, ' ').replace(/\s+/g, ' ').trim() .split(' ').map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)).join(''); const params = extractParams(filePath); if (params.length > 0) { const paramPart = params.map(param => 'By' + param.charAt(0).toUpperCase() + param.slice(1)).join(''); baseFunctionName += paramPart; } return baseFunctionName; }; // Ekstraksi parameter dari path file const extractParams = (filePath) => { const matches = filePath.match(/\[([^\]]+)\]/g); return matches ? matches.map(param => param.replace(/[\[\]]/g, '')) : []; }; // Deteksi metode HTTP dari file API const detectHttpMethod = (fullPath) => { const content = fs_1.default.readFileSync(fullPath, 'utf8'); const match = content.match(/export\s+async\s+function\s+(GET|POST|DELETE|PUT|PATCH)\s*\(/); return match ? match[1].toUpperCase() : 'GET'; }; // Menghasilkan kode fungsi berdasarkan file API const generateFunctionCode = (fullPath, filePath) => { const functionName = generateFunctionName(filePath); const params = extractParams(filePath); const method = detectHttpMethod(fullPath); const paramString = params.map(param => `${param}: string`).join(', '); const paramDestructure = [...params, method === 'POST' && 'body', 'searchParams', 'token'].filter(Boolean).join(', '); const apiPath = filePath.replace(/\[([^\]]+)\]/g, '${$1}').replace(/\\/g, '/').replace('route.ts', ''); return ` async ${functionName}({ ${paramDestructure} }: { ${paramString}${paramString && ", "}${method === 'POST' && "body?: string, "}searchParams?: string, token?: string }) { const headers: any = token ? { 'Authorization': \`Bearer \${token}\` } : {}; try { const res = await fetch(\`/api/${apiPath}\${searchParams || ''}\`, { method: '${method}', headers, ${method === 'POST' && "body,"} cache: "no-cache" }); return await res.json().catch(() => null); } catch { return null; } }`; }; exports.default = generateApi;