Skip to content

Conversation

zephraph
Copy link
Contributor

This adds generation for MSW's handler scaffolding. Ultimately it generates two things:

  1. A factory function called makeHandlers which takes...
  2. An interface called MSWHandlers which defines the types for more ergonomic, custom handlers.

makeHandlers generates the array of rest.[get|put|post|etc] handlers which internally take care of setting up the route and validating params and the body. It also wraps the provided handler for error handling and output formatting.

In this new setup we'll define handlers by their operation name (which should match up with the sdk). Error handling is done via exceptions. So lookupOrg will throw if the org isn't found instead of returning a result. This reduces a ton of boilerplate. Likewise instead of returning res(json(blah)) you can just return values directory.

A handler can return

  1. A number which will be interpreted as a status code
  2. A ResponseTransformer (e.g. json())
  3. A value to be treated as the response

A handler can throw

  1. A number which will be interpreted as a status code
  2. A ResponseTransformer (e.g. json())
  3. A string which will be used as the message for a 400 error

I've laid the groundwork to separate path and query params though I haven't actually done that yet. Hopefully we can tackle that as a follow up. There's a console PR that will be the pair of this that has the real implementation of the MSW setup.

w0(`${isQuery ? "?" : ""}: `);
schemaToTypes(param.schema, io);
w(",");
// To generate separate path and query params
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This bit will generate separate query and path params. All we have to do is turn it on and replace the other references.

Comment on lines +44 to +50
/**
* Custom transformer: convenience function for setting response \`status\` and/or
* \`delay\`.
*
* @see https://mswjs.io/docs/basics/response-transformer#custom-transformer
*/
export function json<B>(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ripped some of the utilities out of the mock-api lib and re-exported them back over there. There's probably a better/cleaner way to share these.

Comment on lines +81 to +93
const successResponse =
conf.responses["200"] ||
conf.responses["201"] ||
conf.responses["202"] ||
conf.responses["204"];

const successTypeRef = contentRef(successResponse);
const successType = successTypeRef
? "Api." + refToSchemaName(successTypeRef)
: "void";

const bodyTypeRef = contentRef(conf.requestBody);
const bodyType = bodyTypeRef ? refToSchemaName(bodyTypeRef) : null;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could probably be dried up, it's basically copied directly from the API generator.

Comment on lines +121 to +138
function validateParams<S extends ZodSchema>(schema: S, req: RestRequest) {
const rawParams = new URLSearchParams(req.url.search)
const params: [string, unknown][] = []
// Ensure numeric params like \`limit\` are parsed as numbers
for (const [name, value] of rawParams) {
params.push([name, isNaN(Number(value)) ? value : Number(value)])
}
const result = schema.safeParse({
...req.params,
...Object.fromEntries(params),
})
if (result.success) {
return { params: result.data }
}
return { paramsErr: json(result.error.issues, { status: 400 }) }
}
Copy link
Contributor Author

@zephraph zephraph Oct 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@david-crespo you'd mentioned cleaning this up in the other PR. I did clean up the types though it's still a bit mixed together. Once we separate out the query and the path params this'll become two functions and I think it'll be cleaner.

"dist/Api.d.ts",
"dist/Api.js",
"dist/Api.mjs",
"dist/chunk-XYDDUAPD.mjs",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went ahead and disabled chunking. It was getting kinda noisy.

@zephraph zephraph requested a review from david-crespo October 13, 2022 03:19
Copy link
Collaborator

@david-crespo david-crespo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heroic. let's party

@zephraph zephraph merged commit 80e229e into main Oct 18, 2022
@zephraph zephraph deleted the add-api-paths-type branch October 18, 2022 18:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants