|
| 1 | +import { createContext } from "./context.ts"; |
| 2 | +import { useScope } from "./scope.ts"; |
| 3 | +import type { Operation, Scope } from "./types.ts"; |
| 4 | + |
| 5 | +/** |
| 6 | + * Serializable name/value pairs that can be used for visualizing and |
| 7 | + * inpsecting Effection scopes. There will always be at least a name |
| 8 | + * in the attributes. |
| 9 | + */ |
| 10 | +export type Attributes = |
| 11 | + & { name: string } |
| 12 | + & Record<string, string | number | boolean>; |
| 13 | + |
| 14 | +const AttributesContext = createContext<Attributes>( |
| 15 | + "@effection/attributes", |
| 16 | + { name: "anonymous" }, |
| 17 | +); |
| 18 | + |
| 19 | +/** |
| 20 | + * Add metadata to the current {@link Scope} that can be used for |
| 21 | + * display and debugging purposes. |
| 22 | + * |
| 23 | + * Calling `useAttributes()` multiple times will add new attributes |
| 24 | + * and overwrite attributes of the same name, but it will not erase |
| 25 | + * old ones. |
| 26 | + * |
| 27 | + * @example |
| 28 | + * ```ts |
| 29 | + * function useServer(port: number): Operation<Server> { |
| 30 | + * return resource(function*(provide) { |
| 31 | + * yield* useAttributes({ name: "Server", port }); |
| 32 | + * let server = createServer(); |
| 33 | + * server.listen(); |
| 34 | + * try { |
| 35 | + * yield* provide(server); |
| 36 | + * } finally { |
| 37 | + * server.close(); |
| 38 | + * } |
| 39 | + * }); |
| 40 | + * } |
| 41 | + * ``` |
| 42 | + * |
| 43 | + * @param attrs - attributes to add to this {@link Scope} |
| 44 | + * @returns an Oeration adding `attrs` to the current scope |
| 45 | + * @since 4.1 |
| 46 | + */ |
| 47 | +export function* useAttributes(attrs: Partial<Attributes>): Operation<void> { |
| 48 | + let scope = yield* useScope(); |
| 49 | + |
| 50 | + let current = scope.hasOwn(AttributesContext) |
| 51 | + ? scope.expect(AttributesContext) |
| 52 | + : AttributesContext.defaultValue!; |
| 53 | + |
| 54 | + scope.set(AttributesContext, { ...current, ...attrs }); |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Get the unique attributes of this {@link Scope}. Attributes are not |
| 59 | + * inherited and only the attributes explicitly assigned to this scope |
| 60 | + * will be returned. |
| 61 | + */ |
| 62 | +export function getAttributes(scope: Scope) { |
| 63 | + if (scope.hasOwn(AttributesContext)) { |
| 64 | + return scope.expect(AttributesContext); |
| 65 | + } |
| 66 | + return AttributesContext.defaultValue as Attributes; |
| 67 | +} |
0 commit comments