Skip to content

v1.1.0

Compare
Choose a tag to compare
@srikrsna-buf srikrsna-buf released this 04 Oct 17:57
· 207 commits to main since this release
ffd41b0

What's Changed

Add support for user provided context values in handlers and clients.

Create a context key with a default value:

export interface User {
  id: string;
}
import { createContextKey } from "@connectrpc/connect";
export const kUser = createContextKey<User | undefined>(
  undefined // The default value.
);

Use the contextValues option to provide the context values for each request:

import { fastify } from "fastify";
import routes from "./connect";
import { fastifyConnectPlugin } from "@connectrpc/connect-fastify";
import { authenticate } from "./authenticate.js"; 
import { kUser } from "./user-ctx.js";

const server = fastify();

await server.register(fastifyConnectPlugin, {
 routes,
 contextValues: (req) => createContextValues().set(kUser, authenticate(req)),
});

await server.listen({
  host: "localhost",
  port: 8080,
});

Use the context value in the handler:

import { ConnectRouter } from "@connectrpc/connect";
import { ElizaService } from "./gen/eliza_connect.js";

export default (router: ConnectRouter) => {
  // using const say
  router.service(ElizaService, {
    say: (req, { values }) => {
      const currentUser = values.get(kUser);
      if (currentUser === undefined) {
        throw new ConnectError("Unauthenticated", Code.Unauthenticated);
      }
      // ...
    },
  });
};

Can be used in clients too:

import { ElizaService } from "gen/...";
import { createPromiseClient } from "@connectrpc/connect";
import transport from "./transport.js";
import kUser from "user-context.js";

const client = createPromiseClient(ElizeService, trasport);

await client.say({ sentence: "Hi" }, { values: createContextValues().set(kUser, { ... }) });

Which can be accessed in an interceptor:

const tokenInterceptor = (next) => {
    return (req) => {
           req.header.set("Authorization", `Bearer ${req.values.get(kUser).token}`);
           return next(req);
    };
};

Enhancements

Bug fixes

  • Fix early event loop exit on nodejs when H2 sessions are in the verify state by @srikrsna-buf in #861
  • Fix type exports and integrate arethetypeswrong by @smaye81 in #838

New Contributors

Full Changelog: v1.0.0...v1.1.0