Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove storage key generic type #64

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions template/src/services/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,61 @@ import { MMKV } from 'react-native-mmkv';
import { singleton } from 'tsyringe';
import EventEmitter from '~/services/event-emitter';

export interface StorageSubscriptionParams<KeyType> {
key: KeyType;
export interface StorageSubscriptionParams {
key: string;
value: any;
}

export type StorageSubscription<KeyType> = (
params: StorageSubscriptionParams<KeyType>
) => void;
export type StorageSubscription = (params: StorageSubscriptionParams) => void;

@singleton()
export default class Storage<KeyType extends string> {
export default class Storage {
constructor(
private eventEmitter: EventEmitter<
'storage',
StorageSubscriptionParams<KeyType>
>
private eventEmitter: EventEmitter<'storage', StorageSubscriptionParams>
) {
this.storage.addOnValueChangedListener((changedKey) => {
this.eventEmitter.emit('storage', {
key: changedKey as KeyType,
value: this.getItem(changedKey as KeyType),
key: changedKey,
value: this.getItem(changedKey),
});
});
}

storage = new MMKV();

getItem(key: KeyType) {
getItem<Value = any>(key: string): Value | null {
const value = this.storage.getString(key);
return value ? JSON.parse(value) : undefined;

if (value === undefined) {
return null;
}

return JSON.parse(value);
}

setItem(key: KeyType, value: any) {
this.storage.set(key, JSON.stringify(value));
setItem(key: string, value: any) {
return this.storage.set(key, JSON.stringify(value));
}

removeItem(key: KeyType) {
removeItem(key: string) {
this.storage.delete(key);
}

clear() {
this.storage.clearAll();
}

contains(key: KeyType) {
contains(key: string) {
return this.storage.contains(key);
}

subscribe(callback: StorageSubscription<KeyType>) {
subscribe(callback: StorageSubscription) {
this.eventEmitter.subscribe('storage', callback);

return () => this.unsubscribe(callback);
}

unsubscribe(callback: StorageSubscription<KeyType>) {
unsubscribe(callback: StorageSubscription) {
this.eventEmitter.unsubscribe('storage', callback);
}
}
Loading