Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

runtimes/js: Added middleware functionality #1631

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

fredr
Copy link
Member

@fredr fredr commented Dec 6, 2024

Adds a way to set custom status codes and an api for passing data from middlewares to the handler.

const mw = middleware(async (req, next) => {
  // add data that can be read from the handler
  req.data.myMiddlewareData = { some: "data" };

  const resp = await next(req);

  // change the status code on the response
  resp.status = 418;

  return resp
});

To access data in the handler

export const get = api(
  { expose: true, method: "GET", path: "/hello/:name" },
  async ({ name }: { name: string }): Promise<Response> => {
    const callMeta = currentRequest() as APICallMeta;
    const myData = callMeta.middlewareData?.myMiddlewareData;

    return { message: "Hello " + name };
  },
);

@fredr fredr self-assigned this Dec 6, 2024
@encore-cla
Copy link

encore-cla bot commented Dec 6, 2024

All committers have signed the CLA.

@fredr fredr force-pushed the fredr/ts-middleware-improvements branch from 2924d37 to 04dd70c Compare December 6, 2024 09:43
@@ -32,6 +55,7 @@ pub fn meta(req: &model::Request) -> Result<RequestMeta, serde_json::Error> {
.map(serde_json::to_value)
.transpose()?,
headers: serialize_headers(&rpc.req_headers),
middleware_data: req.middleware_data.lock()?.clone().map(PVals),
Copy link
Member Author

Choose a reason for hiding this comment

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

I think this should be fine, as there shouldn't be any contention on this lock, but alternatively we can add a function that fetches this data on demand instead

@fredr fredr force-pushed the fredr/ts-middleware-improvements branch from 04dd70c to a2c3481 Compare December 12, 2024 08:55
@fredr fredr force-pushed the fredr/ts-middleware-improvements branch from a2c3481 to 7c5d4ca Compare December 18, 2024 12:56
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.

1 participant