Skip to content

Commit

Permalink
context support set & get data
Browse files Browse the repository at this point in the history
  • Loading branch information
zhmushan committed Aug 6, 2020
1 parent 3859efe commit 09ca677
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export class Context {
params: Record<string, string> = {};
customContext: any;

#store?: Map<string | symbol, unknown>;

get cookies(): Cookies {
return getCookies(this.request);
}
Expand All @@ -54,6 +56,18 @@ export class Context {
return params;
}

get(key: string | symbol): unknown {
return this.#store?.get(key);
}

set(key: string | symbol, val: unknown): void {
if (this.#store === undefined) {
this.#store = new Map();
}

this.#store.set(key, val);
}

constructor(opts: ContextOptions);
constructor(c: Context);
constructor(optionsOrContext: ContextOptions | Context) {
Expand Down
13 changes: 13 additions & 0 deletions context_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,16 @@ test("context custom", function (): void {

assertEquals(cc.hello(), "hello");
});

test("context get set", function (): void {
const c = new Context({ app: undefined!, r: createMockRequest() });

c.set("Hello", "World");
assertEquals(c.get("hello"), undefined);
assertEquals(c.get("Hello"), "World");

const key = Symbol("Hello");
c.set(key, "World");
assertEquals(c.get(Symbol("Hello")), undefined);
assertEquals(c.get(key), "World");
});
13 changes: 13 additions & 0 deletions docs/context.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
## Context

### Data sharing

```ts
app.use((next) => (c) => {
c.set("Name", "Mu Shan");
return next(c);
});

app.get("/", (c) => {
return `Hello ${c.get("Name")}`;
});
```

### Use a custom context

```ts
Expand Down

0 comments on commit 09ca677

Please sign in to comment.