import fs from 'fs';
import path from 'path';
export function generateTypedSWRHookAuto(rootPath: string, apiPath: string, responseType: string) {
const hooksDir = path.join(rootPath, 'hooks');
if (!fs.existsSync(hooksDir)) fs.mkdirSync(hooksDir);
const hookName = 'use' + apiPath.split('/').pop()?.replace(/\W/g, '') + 's';
const code = `
import useSWR from "swr";
import type { ${responseType} } from "../types/${responseType}";
export function ${hookName}() {
const { data,error } = useSWR<${responseType}>("${apiPath}", url=>fetch(url).then(r=>r.json()));
return { data,error,isLoading:!error && !data };
}
`;
const filePath = path.join(hooksDir, `${hookName}.ts`);
fs.writeFileSync(filePath, code);
return filePath;
}