1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | import {
|
18 | addressEvent,
|
19 | HandlerContext,
|
20 | QueryNoCacheOptions,
|
21 | } from "@atomist/automation-client";
|
22 | import { PreferenceStoreFactory } from "@atomist/sdm";
|
23 | import { SdmPreferenceByKey } from "../../typings/types";
|
24 | import {
|
25 | AbstractPreferenceStore,
|
26 | Preference,
|
27 | } from "./AbstractPreferenceStore";
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | export const GraphQLPreferenceStoreFactory: PreferenceStoreFactory = ctx => new GraphQLPreferenceStore(ctx);
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | export class GraphQLPreferenceStore extends AbstractPreferenceStore {
|
41 |
|
42 | constructor(private readonly context: HandlerContext) {
|
43 | super(context);
|
44 | }
|
45 |
|
46 | protected async doGet(name: string, namespace: string): Promise<Preference | undefined> {
|
47 | const key = this.scopeKey(name, namespace);
|
48 | const result = await this.context.graphClient.query<SdmPreferenceByKey.Query, SdmPreferenceByKey.Variables>({
|
49 | name: "SdmPreferenceByKey",
|
50 | variables: {
|
51 | key: [key],
|
52 | },
|
53 | options: QueryNoCacheOptions,
|
54 | });
|
55 | if (!!result.SdmPreference && result.SdmPreference.length === 1) {
|
56 | return {
|
57 | name,
|
58 | namespace,
|
59 | value: result.SdmPreference[0].value,
|
60 | ttl: result.SdmPreference[0].ttl,
|
61 | };
|
62 | }
|
63 | return undefined;
|
64 | }
|
65 |
|
66 | protected doPut(pref: Preference): Promise<void> {
|
67 | const key = this.scopeKey(pref.name, pref.namespace);
|
68 | return this.context.messageClient.send({
|
69 | key,
|
70 | value: pref.value,
|
71 | ttl: typeof pref.ttl === "number" ? Date.now() + pref.ttl : undefined,
|
72 | }, addressEvent("SdmPreference"));
|
73 | }
|
74 |
|
75 | protected async doList(namespace: string): Promise<Preference[]> {
|
76 | const result = await this.context.graphClient.query<SdmPreferenceByKey.Query, SdmPreferenceByKey.Variables>({
|
77 | name: "SdmPreferenceByKey",
|
78 | options: QueryNoCacheOptions,
|
79 | });
|
80 | if (!!result.SdmPreference) {
|
81 | return result.SdmPreference.filter(p => !namespace || p.key.startsWith(`${namespace}_$_`)).map(p => ({
|
82 | name: p.key.includes("_$_") ? p.key.split("_$_")[1] : p.key,
|
83 | namespace: p.key.includes("_$_") ? p.key.split("_$_")[0] : undefined,
|
84 | value: p.value,
|
85 | ttl: p.ttl,
|
86 | }));
|
87 | }
|
88 | return [];
|
89 | }
|
90 |
|
91 | protected async doDelete(name: string, namespace: string): Promise<void> {
|
92 | return this.doPut({ name, namespace, value: undefined, ttl: -100 });
|
93 | }
|
94 |
|
95 | }
|