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.

35 lines (34 loc) 1.5 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, ...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}`); } const response = await fetch(`${baseUrl}/${pathString}${queryParams}`, { ...fetchOptions, method: options.method, headers: options.headers, body: options.body ? JSON.stringify(options.body) : undefined, }); return response; }; return fetchApi; }; exports.createNextFetchApi = createNextFetchApi;