Client Context
Let's reconsider our example function from the introduction (src/services/greet-me.ts
).
src/services/greet-me.ts
import { type Context } from "@quatico/magellan-shared";
import { type Serialization } from "@quatico/magellan-shared";
// @service()
export const greetMe = async (name: string, context?: Context, serialization?: Serialization): Promise<string> => {
// This code must be executed on the server. In the browser, accessing process.arch causes an error.
return `Hello ${name}! I'm Magellan running on "${
typeof window === "undefined" ? `${process.arch}" server` : "browser"
}!`;
};
If we want to provide additional data with each request, we can utilize the context
.
The context
is available both on the client and server.
The Context
type is generic and allows to customize the client
and server
types.
The default types are as follows.
type Context = {
// client context
client?: { headers: Record<string, string> };
// server context
server?: Record<string, string>;
};
When using the default transport handler formdata-fetch.ts
, the content of Context["client"]
is added as request headers to each request.
On the server, the Magellan sdk supports injecting the context into the function execution:
export class Sdk {
public invokeFunction<I, O>(name: string, data: I, namespace = "default", ctx: Context = { server: {} }): Promise<O> {}
}
The content of Context["server"]
is not automatically injected but needs to be done by the server using the Magellan sdk.
export const createFunctionRoute = (sdk = new Sdk()) => {
sdk.init();
const router = Router();
router.post("/", async (req: express.Request, res: express.Response) => {
const { name, data = "{}", namespace = "default" } = req.body;
const parsedData = unpackObject(JSON.parse(data));
// the client provides the request context as headers
const headers = req.headers;
const ctx: Context = {
server: {
// we might want to provide the server's context with the value from the client
"x-request-id": req?.headers?.["x-request-id"] ?? "no-req-id",
"other": "some-static-value-from-the-server"
}
};
const result = await sdk.invokeFunction(name, parsedData, namespace, ctx);
res.status(200).end(result.data);
return;
);
return router;
};