UNPKG

@typespec/http-server-js

Version:

TypeSpec HTTP server code generator for JavaScript

55 lines 2.12 kB
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. /** * Create a function from a chain of policies. * * This returns a single function that will apply the policy chain and eventually call the provided `next()` function. * * @param name - The name to give to the policy chain function. * @param policies - The policies to apply to the request. * @param out - The function to call after the policies have been applied. */ export function createPolicyChain(name, policies, out) { let outParams; if (policies.length === 0) { return out; } function applyPolicy(ctx, index) { if (index >= policies.length) { return out(ctx, ...outParams); } policies[index](ctx, function nextPolicy(nextRequest) { applyPolicy({ ...ctx, request: nextRequest ?? ctx.request, }, index + 1); }); } return { [name](ctx, ...params) { outParams = params; applyPolicy(ctx, 0); }, }[name]; } /** * Create a policy chain for a given route. * * This function calls `createPolicyChain` internally and orders the policies based on the route configuration. * * Interface-level `before` policies run first, then method-level policies, then Interface-level `after` policies. * * @param name - The name to give to the policy chain function. * @param routePolicies - The policies to apply to the routes (part of the route configuration). * @param interfaceName - The name of the interface that the route belongs to. * @param methodName - The name of the method that the route corresponds to. * @param out - The function to call after the policies have been applied. */ export function createPolicyChainForRoute(name, routePolicies, interfaceName, methodName, out) { return createPolicyChain(name, [ ...(routePolicies[interfaceName]?.before ?? []), ...(routePolicies[interfaceName]?.methodPolicies?.[methodName] ?? []), ...(routePolicies[interfaceName]?.after ?? []), ], out); } //# sourceMappingURL=router.js.map