Add a type-safe way to define custom methods in @payloadcms/sdk
#17965
vqhdev
started this conversation in
Feature Requests & Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
It would be useful if
@payloadcms/sdkhad a built-in way to define custom, fully typed methods on top ofsdk.request().Right now, custom endpoints can be called with
sdk.request(), which works well as a low-level API:The problem is that every call site needs to know the exact path, method, and request body expected by the endpoint.
For custom endpoints, TypeScript also does not know the expected request body unless the consumer defines and applies those types manually. This makes mistakes like these easy to introduce:
From TypeScript's point of view, this can still be a valid
sdk.request()call even though it does not match what the custom endpoint expects.It would be nice to define that contract once and expose it as a normal SDK method:
Then TypeScript could immediately catch invalid calls:
The endpoint path and HTTP method would also live in one place instead of being repeated throughout the application.
There are a couple of APIs that could support this.
Option 1: Define custom methods in the constructor
Usage:
Option 2: Add an
.extend()methodUsage would be the same:
The
.extend()approach could also make reusable groups of methods possible:The main idea is not to replace
sdk.request(). It would still be useful as the low-level escape hatch.This would provide a higher-level API for custom endpoints where the path, HTTP method, request type, and response type can be defined once. Consumers could then call custom endpoints like regular SDK methods and get TypeScript errors immediately when an argument is missing or has the wrong type.
I think this would make custom endpoints safer to use and reduce duplicated request definitions across an application.
Would something like this make sense for
@payloadcms/sdk?All reactions