UNPKG

2.32 kBPlain TextView Raw
1/*
2 * Copyright © 2019 Atomist, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import { HandlerContext } from "@atomist/automation-client";
18import { PreferenceStoreFactory } from "@atomist/sdm";
19import * as _ from "lodash";
20import {
21 AbstractPreferenceStore,
22 Preference,
23} from "./AbstractPreferenceStore";
24
25/**
26 * Factory to create a new InMemoryPreferenceStore instance
27 */
28export const InMemoryPreferenceStoreFactory: PreferenceStoreFactory = ctx => new InMemoryPreferenceStore(ctx);
29
30/**
31 * PreferenceStore implementation that simply stores preferences in-memory.
32 * Note: This is implementation is not intended for production usage.
33 */
34export class InMemoryPreferenceStore extends AbstractPreferenceStore {
35
36 private readonly store: { [key: string]: Preference } = {};
37
38 constructor(context: HandlerContext) {
39 super(context);
40 }
41
42 protected async doGet(name: string, namespace: string): Promise<Preference | undefined> {
43 const key = this.scopeKey(name, namespace);
44 return this.store[key];
45 }
46
47 protected async doPut(pref: Preference): Promise<void> {
48 const key = this.scopeKey(pref.name, pref.namespace);
49 this.store[key] = {
50 ...pref,
51 ttl: typeof pref.ttl === "number" ? Date.now() + pref.ttl : undefined,
52 };
53 }
54
55 protected async doList(namespace: string): Promise<Preference[]> {
56 const values: Preference[] = [];
57 _.forEach(this.store, (v, k) => {
58 if (!namespace || k.startsWith(`${namespace}_$_`)) {
59 values.push(v);
60 }
61 });
62 return values;
63 }
64
65 protected async doDelete(name: string, namespace: string): Promise<void> {
66 const key = this.scopeKey(name, namespace);
67 delete this.store[key];
68 }
69}