Skip to content

tRPC to OpenAPI generator #1724

Closed
Closed

Description

@KATT

Note: I do not want to have this as part of the library itself, but an example would be good

Overview

With the addition of output parser (#1699), we should now have all the pieces to automatically create an OpenAPI-compliant endpoint

Some rough ideas:

A starting point for the api handler:

import { ProcedureType, TRPCError } from '@trpc/server';
import { NextApiRequest, NextApiResponse } from 'next';
import { createContext } from '~/server/context';
import { appRouter } from '~/server/routers/_app';

export default async function swag(req: NextApiRequest, res: NextApiResponse) {
  const { params, ...queryParams } = req.query;
  if (req.method !== 'POST' && req.method !== 'GET') {
    res.status(405).json({
      message: 'Invalid method',
    });
    return;
  }
  const path = Array.isArray(params) ? params.join('/') : params;
  const ctx = await createContext({ req, res });
  const type: ProcedureType = req.method === 'POST' ? 'mutation' : 'query';
  try {
    const caller = appRouter.createCaller({ ctx });

    const fn = caller[type] as any;
    const result = await fn(path, queryParams);

    res.json(result);
    return;
  } catch (error) {
    if (!(error instanceof TRPCError)) {
      res.status(500).json({
        message: 'Something went wrong',
      });
      return;
    }
    const formatted = appRouter.getErrorShape({
      error,
      path,
      ctx,
      input: params,
      type,
    });
    // TODO: use https://github.com/trpc/trpc/blob/main/packages/server/src/http/internals/getHTTPStatusCode.ts#L55-L59
    // Feel free to make them publicly exposed
    const status = 500;
    res.status(500).json(formatted);
  }
}

Activity

  1. LouisHaftmann commented on Apr 6, 2022

    @LouisHaftmann
    Contributor

    Would this be used to generate mutation/query routes that comply to the OpenAPI specification or just to generate a swagger schema?

  2. KATT commented on Apr 6, 2022

    @KATT
    MemberAuthor

    Would this be used to generate mutation/query routes that comply to the OpenAPI specification or just to generate a swagger schema?

    Ideally both. We should have all the information needed to create a new api handler and automatically expose a REST-esque version of trpc

  3. KATT commented on Apr 6, 2022

    @KATT
    MemberAuthor

    With #1736 we should be able to give hints too to remap paths or to say that something should be a PUT/PATCH/DELETE method

  4. jlalmes commented on Apr 7, 2022

    @jlalmes
    Contributor

    Proposal tRPC <> OpenAPI

    Sharing my thoughts regarding OpenAPI support.

    • Publish new package under @trpc/openapi

    01. Router

    We will export a openApiRouter() function that will return an OpenApiCompliantRouter that extends Router.

    02. Generator

    We will export a createOpenApiSchema() function that will accept a OpenApiCompliantRouter and return an OpenAPIV3.Document (https://www.npmjs.com/package/openapi-types). This will generate the parameters(query)/requestBody(mutation) schema and responseBody schema using the inputParser and outputParser validators defined on the procedure. The generated OpenAPI spec will use meta.openapi metadata where applicable.

    export type OpenApiResponse<TData = any> = { ok: true; data: TData } | { ok: false; error: DefaultErrorShape };

    03. Adapters

    We will export createHTTPOpenApiHandler(), createHTTPOpenApiServer(), createExpressOpenApiMiddleware(), createNextOpenApiHandler(), fastifyTRPCOpenApiPlugin() functions. These should be drop-in replacements for their @trpc/server counterparts, except for the following changes:

    • The provided router must be typeof OpenApiCompliantRouter.
    • Request batching is not supported.

    Example usage

    // server.ts
    import express from 'express';
    import { z } from 'zod';
    import { createExpressMiddleware } from '@trpc/openapi';
    import { openApiRouter, createOpenApiSchema, createExpressOpenApiMiddleware } from '@trpc/openapi';
    
    const router = openApiRouter().query('greeting', {
      input: {
        name: z.string(),
      },
      output: {
        greeting: z.string(),
      },
      meta: {
        openapi: {
          method: 'GET',
          description: 'Returns a personalised greeting`,
        },
      },
      resolver: ({ input }) => {
        return {
          greeting: `Hello ${input.name}!`,
        };
      }
    });
    
    const openApiSchema = createOpenApiSchema(openApiRouter, { title: 'tRPC API' });
    
    const app = express();
    
    app.use('/trpc', createExpressMiddleware({ router }));
    app.get('/public/schema', (req, res) => res.status(200).send(openApiSchema));
    app.use('/public', createExpressOpenApiMiddleware({ router }));
    
    app.listen(8000);
    // client.ts
    const body = await fetch('http://localhost:8000/public/greeting?name=James').then((res) => res.json());
    // => { 
    //   ok: true, 
    //   data: { 
    //     greeting: 'Hello James!' 
    //   } 
    // };

    Happy to hear any feedback!

  5. KATT commented on Apr 7, 2022

    @KATT
    MemberAuthor

    I am not sure if I am ready to commit to maintaining a new sub-library for a use-case that I don't have use for myself. I am all for having the necessary hooks to enable this, but I don't know if I want to make an official @trpc/openapi-package.

    How I would see this working:

    // server/router.ts:
    import trpc from '@trpc/server'
    import {Context} from './context'
    
    type HTTPMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'
    interface Meta {
      openapi?: {
        method: HTTPMethod;
      }
    }
    
    function createRouter<Context, Meta>() {
      return trpc.router<Context, Meta>
    }
    • The createOpenApiSchema as suggested above could be a completely standalone package or just a reference project to start with.
    • It can automatically include the routes that have meta.openapi and ignore the rest - it's pretty common to only have some methods publicly exposed
    • The api handlers (/public/, public/schema) are handled in said helper
  6. LouisHaftmann commented on Apr 7, 2022

    @LouisHaftmann
    Contributor

    A plugin system (#1742) would probably be more usefull because it allows users to create all kinds of plugins (including an openapi plugin)

  7. Brian-McBride commented on Apr 12, 2022

    @Brian-McBride

    The main reason I would like to have an OpenAPI spec generator is just to have an easier integration with all the various cloud-based API Gateways. Nearly all of them have the step of defining the API Proxy with an OpenAPI schema.

  8. jlalmes commented on Apr 12, 2022

    @jlalmes
    Contributor

    @Brian-McBride I plan to publish my trpc-openapi work promptly after tRPC v10 is released.

  9. mwarger commented on May 23, 2022

    @mwarger
    Contributor

    This would be fantastic, as I think it could also be used with this: https://github.com/api-platform/admin

  10. jlalmes commented on May 23, 2022

    @jlalmes
    Contributor

    You can try out the alpha release of trpc-openapi that is compatible with the current stable version of @trpc/server@9. Bear in mind that the API may change before official release.

    https://www.npmjs.com/package/trpc-openapi

  11. Brian-McBride commented on May 24, 2022

    @Brian-McBride

    @jlalmes Would it work with the Fastify adaptor?

  12. jlalmes commented on May 24, 2022

    @jlalmes
    Contributor

    Absolutely! We would just need to add a fastifyOpenApiRequestHandler & fastifyTRPCOpenApiPlugin adapter here: https://github.com/jlalmes/trpc-openapi/tree/v0.1.0/src/adapters. I am not familiar with Fastify so can't be too much help, but happy to assist where possible if you want to open a PR.

    Here's a good starting point: https://github.com/trpc/trpc/tree/main/packages/server/src/adapters/fastify

  13. jlalmes commented on Jun 10, 2022

    @jlalmes
    Contributor

    For tRPC to OpenAPI compliant endpoints & schema generator, please use trpc-openapi: https://github.com/jlalmes/trpc-openapi

  14. github-actions commented on Oct 4, 2022

    @github-actions
    Contributor

    This issue has been locked because it had no new activity for 14 days. If you are running into a similar issue, please create a new issue. Thank you.

  15. locked as resolved and limited conversation to collaborators on Oct 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions