3 ms·
Huh - interesting. I built something similar at work. I didn't do a perfect job - you need to manually write in an endpoint spec that points to each controller
by teaearlgraycold 5y ago
Huh - interesting. I built something similar at work. I didn't do a perfect job - you need to manually write in an endpoint spec that points to each controller method. For example:
/**
* Add new survey answer.
*/
// prettier-ignore
export type AddSurveyAnswer = PostEndpoint<`/survey/survey-answer/${string}`, never, Validators.SurveyAnswerBody, ResponseDataType<typeof SurveyController, "addSurveyAnswer">>;
But really the only duplicated information is the HTTP verb and the path. And those won't change very often - if at all.
Then in the front end you import the file containing all of the endpoint types:
import * as API from "@copy-ai/endpoints";
And you're good to make requests:
const response = await request<API.AddSurveyAnswer>({
url: `/survey/survey-answer/${questionId}`,
method: "post",
data: surveyAnswerBody,
});
You might wonder - why are you making me retype the URL/method? You don't really have to. Your editor will auto-fill that as the method can be extracted from the endpoint type as the type "post". Not a string - "post". Same for the path, but we use parameterized string types.
There's no magic here. What's happening is pretty transparent to the programmer. We just tuck away the PostEndpoint etc. types as those don't ever need to get changed. You can even easily YOLO an API request by passing in the any type.