UNPKG

next-ts-api

Version:

A powerful TypeScript-first API client generator for Next.js applications with full type safety and automatic api type generation.

46 lines (45 loc) 1.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createNextFetchApi = void 0; const logger_1 = require("./lib/logger"); /** * Creates a typed fetch API for API routes * @template AT - The API routes type * @returns A function that can be used to fetch data from API routes */ const createNextFetchApi = ({ baseUrl = '/api' } = {}) => { const fetchApi = async (path, options) => { let pathString = path; const { query, params, body, form, ...fetchOptions } = options; const definedQuery = query ? Object.fromEntries(Object.entries(query).filter(([_, value]) => value !== undefined)) : {}; const queryParams = query ? `?${new URLSearchParams(definedQuery)}` : ''; if (params) { Object.entries(params).forEach(([key, value]) => { pathString = pathString.replace(`[${key}]`, value); }); const missingParams = pathString.match(/\[([^\]]+)\]/g)?.map(param => param.slice(1, -1)); if (missingParams) logger_1.logger.error(`Missing required params for ${pathString}`); } let payload = undefined; if (form) { const formData = new FormData(); for (const key in form) { formData.append(key, form[key]); } payload = formData; } else if (body) { payload = JSON.stringify(body); } const response = await fetch(`${baseUrl}/${pathString}${queryParams}`, { ...fetchOptions, method: options.method, headers: options.headers, body: payload, }); return response; }; return fetchApi; }; exports.createNextFetchApi = createNextFetchApi;