Skip to main content

post()

Function Signature

post: <T>(api?: string, data?: unknown) => DenchCreateBuilder<T>
{
method: 'POST'
}

Description

Returns a DenchCreateBuilder<T> for configuring a POST request. Use the returned builder to select a body format and then call a runner method.

The generic type T represents the TypeScript type of the JSON response returned later by toJson().

Example

import { dench } from 'dench-fetch';

type CreatedUser = {
id: number;
name: string;
};

const api = dench('https://api.example.com');

const user = await api
.post<CreatedUser>('/users')
.sendJson({ name: 'Dench' })
.toJson();

Immediately after post(), the RequestInit is:

{
method: 'POST'
}

After applying sendJson(), the executed request is equivalent to:

fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Dench' }),
});

Notes

  • The type declaration includes a second data parameter, but the current implementation does not use it as the request body.
  • Pass the request body to a method on the returned builder, such as sendJson(data) or sendForm(data).
  • Calling post() does not execute the request.