Skip to content

Some questions I can't find the solution #4

@emretfn

Description

@emretfn

Hi, appreciate your solutions like better-auth, better-call and better-fetch. I have some questions that I cannot find a solution due to lack of documentation. I hope with v1.0 we can get a proper documentation. First let me explain how I created the endpoints and how I use the router.

First I create an endpoint and export it

import { createEndpoint, APIError } from "better-call";
import { z } from "zod";

const posts: { id: number; title: string; content: string }[] = [];

const getRecentPost = createEndpoint(
  "/post/recent",
  {
    method: "GET",
    requireRequest: true,
  },
  async () => {
    if (posts.length <= 0) {
      throw new APIError("BAD_REQUEST", {
        foo: "bar",
      });
    }
    return posts[posts.length - 1];
  }
);


const postsEndpoints = {
  getRecentPost,
};

export default postsEndpoints;

Then I pass these endpoints to createRouter.

import { createRouter } from "better-call";
import postsEndpoints from "./routes/post";

export const router = createRouter(
  {
    ...postsEndpoints,
  },
  {
    basePath: "/api",
  }
);

Finally, I create an RPC client and use it on the frontend side.

//client.ts
import { router } from "@/server";
import { createClient } from "better-call/client";

export const api = createClient<typeof router>({
  baseURL: "http://localhost:3000/api",
});

Now let me tell you about my questions.

  1. I pass foo as a custom key where I throw APIError, but this foo is not in the type of the error object when using the RPC Client.
    Image

  2. If I do not add ‘requireRequest: true’ between the options of the createEndpoint function. The RPC client expects me to pass ctx (passing an empty object solves the problem but not what I want). In this way, I have to add requireRequest to all requests, is there a method I can make it true as default value?
    Image

  3. How can I add the db to the handler ctx to use in all createEndpoint functions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions