ts-rest / ts-rest

RPC-like client, contract, and server implementation for a pure REST API
https://ts-rest.com
MIT License
2.11k stars 91 forks source link

Add support/docs for listenTerminalRoute (SSE) #594

Closed kristianmandrup closed 1 month ago

kristianmandrup commented 2 months ago

Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

I'm trying to use @ts-rest/fastify with Server Side Events (SSE). It was unclear if or how I could do it. I found the following snippet as part of the @ts-rest/fastify implementation and it seems to allow reply as an option argument for the routeImpl which was not clear. This should let me do reply.sse(...)

const registerRoute = (routeImpl, appRoute, fastify, options) => {
    if (options.logInitialization) {
        console.log(`[ts-rest] Initialized ${appRoute.method} ${appRoute.path}`);
    }
    fastify.route({
        method: appRoute.method,
        url: appRoute.path,
        handler: async (request, reply) => {
            const validationResults = validateRequest(request, reply, appRoute, options);
            let result;
            try {
                result = await routeImpl({
                    params: validationResults.paramsResult.data,
                    query: validationResults.queryResult.data,
                    headers: validationResults.headersResult.data,
                    request,
                    body: validationResults.bodyResult.data,
                    reply,
                    appRoute,
                });
            }

ChatGPT helped me out, suggestion the following routeImpl code for my use case

// Route handler function for listening for terminal output updates via SSE
export async function listenTerminalRoute(
  { params }: FastifyRequest<{ Params: RouterListenTerminalParams }>,
  reply: FastifyReply
): Promise<RouterListenTerminalResult> {
  const { sessionId, channel } = params;

  // Check if the sessionId is valid
  if (!userSessions.has(sessionId)) {
    return { status: 400, body: { message: "Invalid sessionId" } };
  }

Describe the solution you'd like A clear and concise description of what you want to happen.

Please make this feature capability more clear in the docs, perhaps with an example in the docs or the code. Thanks I'll try it out myself now.

Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

You could also perhaps also add a thin wrapper for SSE in the SDK/API?

Additional context Add any other context or screenshots about the feature request here.

Gabrola commented 1 month ago

SSE is beyond the scope of ts-rest as event schemas are inherently not defined by paths, headers, or anything similar.