extHostMemento.ts 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { IDisposable } from 'vs/base/common/lifecycle';
import { IExtensionMemento } from 'vs/workbench/api/common/extHostExtensionActivator';
import { ExtHostStorage } from 'vs/workbench/api/common/extHostStorage';

export class ExtensionMemento implements IExtensionMemento {

	private readonly _id: string;
	private readonly _shared: boolean;
	private readonly _storage: ExtHostStorage;

	private readonly _init: Promise<ExtensionMemento>;
17
	private _value?: { [n: string]: any; };
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
	private readonly _storageListener: IDisposable;

	constructor(id: string, global: boolean, storage: ExtHostStorage) {
		this._id = id;
		this._shared = global;
		this._storage = storage;

		this._init = this._storage.getValue(this._shared, this._id, Object.create(null)).then(value => {
			this._value = value;
			return this;
		});

		this._storageListener = this._storage.onDidChangeStorage(e => {
			if (e.shared === this._shared && e.key === this._id) {
				this._value = e.value;
			}
		});
	}

	get whenReady(): Promise<ExtensionMemento> {
		return this._init;
	}

41 42 43
	get<T>(key: string): T | undefined;
	get<T>(key: string, defaultValue: T): T;
	get<T>(key: string, defaultValue?: T): T {
44
		let value = this._value![key];
45 46 47 48 49 50
		if (typeof value === 'undefined') {
			value = defaultValue;
		}
		return value;
	}

51
	update(key: string, value: any): Promise<void> {
52 53
		this._value![key] = value;
		return this._storage.setValue(this._shared, this._id, this._value!);
54 55 56 57 58 59
	}

	dispose(): void {
		this._storageListener.dispose();
	}
}