Coder Social home page Coder Social logo

Comments (2)

sinclairzx81 avatar sinclairzx81 commented on June 3, 2024

@Jnig Hi, that would be pretty cool, unfortunately I'm not sure I can add this to fastify-typebox as it would conflict with typical reply.status(...).send(...) usage (where users would need to return the same data they sent with the reply).

However, if you would like to experiment, here is the types to make it happen. This creates a union of all status code response types, so you would need to return one of them on the request handler.

// New: Extracts a union of all possible status codes. If no response is specified, this will
// return unknown, if no status codes are specified, then it also returns unknown. 
export type FastifyTypeBoxHandlerMethodReturnType<T extends FastifyTypeBoxSchema> =
    T['response'] extends undefined ? unknown :
    keyof T['response'] extends never ? unknown : 
    ({ 
        [K in keyof T['response']] : Static<T['response'][K]>
    })[keyof T['response']]


export type FastifyTypeBoxHandlerMethod<
    Server extends RawServerBase, 
    Schema extends FastifyTypeBoxSchema,
    Url    extends string
> = (
    request: FastifyTypeBoxRequest<Server, Schema, Url>, 
    reply:   FastifyTypeBoxReply<Schema>
) => FastifyTypeBoxHandlerMethodReturnType<Schema> |  Promise<FastifyTypeBoxHandlerMethodReturnType<Schema>>

Which enables the following type checking behavior.

fastify.get('/', {
    schema: {
        response: {
            200: Type.String(),
            201: Type.Tuple([Type.String(), Type.Number()]),
            202: Type.Object({ x: Type.Number(), y: Type.Number() })
        }
    },
}, async () => {
    // return 42                                // fail: not in union
    // return ['hello', 42]                     // fail: needs const assertion
    
    // return 'hello'                           // ok
    // return ['hello', 42] as [string, number] // ok
     return { x: 1, y: 2 }                      // ok
})

Perhaps one possible solution to there being multiple ways to return a response may be to have .send(T) return T, so implementations require users to return on .send(..), as follows.

{
   schema: {
      response: {
        200: Type.String()
      }
   }
}, (req, reply) => {
   return reply.status(200).send('foo') // send returns 'string'
})

However, I feel this might change fastify's interface a bit too much, but it is worth exploring.

If you're interested, I'm currently working trying to bring some of this functionality into Fastify itself. There is an active PR in process which you can find here which implements a new Fastify feature called Type Providers. As such I may transition this project into a prototyping library to help explore how static typing could enhance the overall Fastify experience for TypeScript / TypeBox users.

Hey, thanks for having a look at the types and experimenting around, all suggestions are worth discussing and thinking about!

Cheers
S

from fastify-typebox.

Jnig avatar Jnig commented on June 3, 2024

Hi,

thank you for your fast and kind reply. I understand that this would conflict with the typical use case. It's probably just a matter of getting used to reply.status(...).send(...) .

Based on your code snippet I have experimented to build a wrapper function that uses only the status code 200. This seems to work well, even if it looks a bit hacky.

So it is possible to create a shortcut if needed and I think the issue can be closed.

The Type Providers PR also looks very promising. Looking forward to the PR being merged!

const fastify = Fastify();

export type FastifyTypeBoxHandlerMethodReturnType<T extends FastifyTypeBoxSchema> =
  T['response'] extends undefined ? unknown : Static<T['response']>;

export type FastifyTypeBoxHandlerMethodSimple<
  Server extends RawServerBase,
  Schema extends FastifyTypeBoxSchema,
  Url extends string,
> = (
  request: FastifyTypeBoxRequest<Server, Schema, Url>,
  reply: FastifyTypeBoxReply<Schema>,
) =>
  | FastifyTypeBoxHandlerMethodReturnType<Schema>
  | Promise<FastifyTypeBoxHandlerMethodReturnType<Schema>>;

function simple200<Url extends string, Schema extends FastifyTypeBoxSchema>(
  url: Url,
  options: FastifyTypeBoxRouteOptions<Server, Schema, any>,
  handler: FastifyTypeBoxHandlerMethodSimple<Server, Schema, Url>,
) {
  if (options?.schema?.response) {
    options.schema.response = {200: options.schema.response as TSchema};
  }

  fastify.get(url, options, async (request, reply) => {
    reply.status(200).send(await handler(request, reply));
  });
}

simple200(
  '/users/:userId',
  {
    schema: {
      querystring: Type.Object({
        x: Type.Number(),
        y: Type.Number(),
      }),
      response: Type.Object({
        result: Type.Number(),
      }),
    },
  },
  async (request, reply) => {
    const { x, y } = request.query;

    return { resu2lt: x + y };
  },
);

simple200(
  '/users/:userId',
  {
    schema: {
      querystring: Type.Object({
        x: Type.Number(),
        y: Type.Number(),
      }),
      response: Type.Object({
        result: Type.Number(),
      }),
    },
  },
  async (request, reply) => {
    const { x, y } = request.query;

    return { result: x + y };
  },
)

image

from fastify-typebox.

Related Issues (4)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.