Skip to content

Instantly share code, notes, and snippets.

@omar2205
Created June 5, 2025 19:31
Show Gist options
  • Save omar2205/4ca1fec5aeee34cd06be7afea9e0e1b9 to your computer and use it in GitHub Desktop.
Save omar2205/4ca1fec5aeee34cd06be7afea9e0e1b9 to your computer and use it in GitHub Desktop.
create api method
/// ref
export const get = async (url: string, input: Record<string, string>) => {
return fetch(`${url}?${new URLSearchParams(input).toString()}`)
}
export const post = async (url: string, input: Record<string, string>) => {
return fetch(url, {
method: 'POST',
body: JSON.stringify(input),
})
}
type CreateAPIMethod = <TInput extends Record<string, string>, TOutput>(opts: {
url: string
method: 'GET' | 'POST'
}) => (input: TInput) => Promise<TOutput>
const createAPIMethod: CreateAPIMethod = (opts) => (input) => {
const method = opts.method === 'GET' ? get : post
return (
method(opts.url, input)
// Imagine error handling here...
.then((res) => res.json())
)
}
/**
* You can reuse this function as many times as you
* like to create all your API methods!
*/
const getUser = createAPIMethod<
{ id: string }, // The input
{ name: string } // The output
>({
method: 'GET',
url: '/user',
})
getUser({ id: 123 }) // All type safe!
@omar2205
Copy link
Author

omar2205 commented Jun 13, 2025

Axios

import axios, { type AxiosRequestConfig } from 'axios'

export const get = async (
  url: string,
  input: Record<string, string>,
  config?: AxiosRequestConfig,
) => {
  return axios.get(url, { ...config, params: input })
}

export const post = async (
  url: string,
  input: Record<string, string>,
  config?: AxiosRequestConfig,
) => {
  return axios.post(url, input, config)
}

type CreateAPIMethod = <TInput extends Record<string, string>, TOutput>(opts: {
  url: string
  method: 'GET' | 'POST'
}) => (input: TInput, config?: AxiosRequestConfig) => Promise<TOutput>

const createAPIMethod: CreateAPIMethod = (opts) => async (input, config) => {
  const method = opts.method === 'GET' ? get : post

  const response = await method(opts.url, input, config)
  return response.data
}

/**
 * You can reuse this function as many times as you
 * like to create all your API methods!
 */
const getUser = createAPIMethod<
  { id: string }, // The input
  { name: string } // The output
>({
  method: 'GET',
  url: '/user',
})

const u = await getUser({ id: 123 }) // All type safe!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment