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

feat(types): turn LocalForageWrapper into a generic class #528

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
20 changes: 9 additions & 11 deletions src/storageWrappers/LocalForageWrapper.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { PersistentStorage } from '../types';

export class LocalForageWrapper
implements PersistentStorage<string | object | null> {
export class LocalForageWrapper<T = string | object | null>
implements PersistentStorage<T>
{
protected storage;

constructor(storage: LocalForageInterface) {
constructor(storage: LocalForageInterface<T>) {
this.storage = storage;
}

getItem(key: string): Promise<string | null> {
getItem(key: string): Promise<T | null> {
return this.storage.getItem(key);
}

removeItem(key: string): Promise<void> {
return this.storage.removeItem(key);
}

setItem(key: string, value: string | object | null): Promise<void> {
setItem(key: string, value: T | null): Promise<void> {
return new Promise((resolve, reject) => {
this.storage
.setItem(key, value)
Expand All @@ -26,12 +27,9 @@ export class LocalForageWrapper
}
}

interface LocalForageInterface {
export interface LocalForageInterface<T = string | object | null> {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I exported LocalForageInterface here as it could be useful.

I'm currently writing a wrapper for LocalForageWrapper that compresses the cache into a binary, so I need both the generic class and the interface here because I need to use composition over inheritance to be able to turn LocalForageWrapper into PersistentStorage<Uint8Array>, but make sure the newly created wrapper exposes string.

// Actual type definition: https://github.com/localForage/localForage/blob/master/typings/localforage.d.ts#L17
getItem(key: string): Promise<string | null>;
setItem(
key: string,
value: string | object | null,
): Promise<string | object | null>;
getItem(key: string): Promise<T | null>;
setItem(key: string, value: T | null): Promise<T | null>;
removeItem(key: string): Promise<void>;
}