-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathhandlerStorage.ts
More file actions
61 lines (55 loc) · 1.65 KB
/
handlerStorage.ts
File metadata and controls
61 lines (55 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { ActiveAuthorizationHandler } from './types'
import { TurnContext } from '../../turnContext'
import { Storage } from '../../storage'
/**
* Storage manager for handler state.
*/
export class HandlerStorage<TActiveHandler extends ActiveAuthorizationHandler = ActiveAuthorizationHandler> {
/**
* Creates an instance of the HandlerStorage.
* @param storage The storage provider.
* @param context The turn context.
*/
constructor (private storage: Storage, private context: TurnContext) { }
/**
* Gets the unique key for a handler session.
*/
public get key (): string {
const channelId = this.context.activity.channelId?.trim()
const userId = this.context.activity.from?.id?.trim()
if (!channelId || !userId) {
throw new Error(`Both 'activity.channelId' and 'activity.from.id' are required to generate the ${HandlerStorage.name} key.`)
}
return `auth/${channelId}/${userId}`
}
/**
* Reads the active handler state from storage.
*/
public async read (): Promise<TActiveHandler | undefined> {
const ongoing = await this.storage.read([this.key])
return ongoing?.[this.key]
}
/**
* Writes handler state to storage.
*/
public write (data: TActiveHandler) {
return this.storage.write({ [this.key]: data })
}
/**
* Deletes handler state from storage.
*/
public async delete () {
try {
await this.storage.delete([this.key])
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 404) {
return
}
throw error
}
}
}