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

Thread through types #4

Merged
merged 4 commits into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fp-ts-indexeddb",
"version": "0.1.5",
"version": "0.2.0",
"description": "Simple FP-TS based wrapper around indexedDB",
"main": "dist/lib/index.js",
"module": "dist/es2015/index.js",
Expand All @@ -27,7 +27,8 @@
],
"contributors": [
"Justin Leider https://github.com/jleider",
"Harim Tejada https://github.com/harimtejada"
"Harim Tejada https://github.com/harimtejada",
"Wolfgang Mcrae https://github.com/Wolfgang-stack"
],
"license": "MIT",
"bugs": {
Expand Down
97 changes: 41 additions & 56 deletions src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,30 @@ import * as R from 'fp-ts/lib/Record';
import * as TE from 'fp-ts/lib/TaskEither';

import * as t from 'io-ts';
import type { ReadonlyRecord } from 'fp-ts/lib/ReadonlyRecord';
import { pipe } from 'fp-ts/lib/function';

type StoreName = string;
type Store = { key: string, codec: t.Mixed };
type Store<StoreC extends t.Mixed> = { key: string, codec: StoreC };

export type DBSchema = {
export type DBSchema<StoreC extends t.Mixed> = {
version: number;
stores: Record<StoreName, Store>;
stores: ReadonlyRecord<StoreName, Store<StoreC>>;
};

export type DBSchemas = DBSchema[];
export type DatabaseInfo = { database: IDBDatabase, schema: DBSchema };
export type DBSchemas<StoreC extends t.Mixed> = ReadonlyArray<DBSchema<StoreC>>;
export type DatabaseInfo<StoreC extends t.Mixed> = { database: IDBDatabase, schema: DBSchema<StoreC> };
export type IndexedDbError = DOMException | Error;

const isError = (u: unknown): u is Error => typeof u === 'object' && u !== null && 'name' in u && 'message' in u;
const isDOMException = (u: unknown): u is DOMException => typeof u === 'object' && u != null && 'code' in u && 'message' in u && 'name' in u;

const handlePromiseError = (u: unknown): IndexedDbError => isError(u) || isDOMException(u) ? u : new Error(`Unhandled error: ${u}`);

const getObjectStore = (db: DatabaseInfo, mode: IDBTransactionMode) => (storeName: string): IDBObjectStore =>
const getObjectStore = <StoreC extends t.Mixed>(db: DatabaseInfo<StoreC>, mode: IDBTransactionMode) => (storeName: string): IDBObjectStore =>
db.database.transaction(storeName, mode).objectStore(storeName);

const findStore = (db: DatabaseInfo, storeName: string) => pipe(
const findStore = <StoreC extends t.Mixed>(db: DatabaseInfo<StoreC>, storeName: string) => pipe(
db.schema.stores,
R.lookup(storeName)
);
Expand All @@ -37,16 +38,16 @@ const handleRequestError = <A>(req: IDBRequest<A>, fn: (error: O.Option<DOMExcep
});
};

export const open = (
export const open = <StoreC extends t.Mixed>(
dbName: string,
schema: DBSchema,
): TE.TaskEither<IndexedDbError, DatabaseInfo> => {
const initDb = () => new Promise<DatabaseInfo>((resolve, reject) => {
schema: DBSchema<StoreC>,
): TE.TaskEither<IndexedDbError, DatabaseInfo<StoreC>> => {
const initDb = () => new Promise<DatabaseInfo<StoreC>>((resolve, reject) => {
// eslint-disable-next-line no-undef
const req = window.indexedDB.open(dbName, schema.version);
req.onupgradeneeded = () => pipe(
schema.stores,
R.mapWithIndex((storeName: string, v: Store) => req.result.createObjectStore(storeName, { keyPath: v.key }))
R.mapWithIndex((storeName: string, v: Store<StoreC>) => req.result.createObjectStore(storeName, { keyPath: v.key }))
);

req.onsuccess = () => resolve({ database: req.result, schema: schema });
Expand All @@ -58,70 +59,54 @@ export const open = (
);
};

export const insert = <A>(
db: DatabaseInfo,
export const insert = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
) => (v: A): TE.TaskEither<IndexedDbError, A> =>
) => (v: StoreC['_A']): TE.TaskEither<IndexedDbError, StoreC['_A']> =>
TE.tryCatch(
() => new Promise<A>((resolve, reject) => {
() => new Promise<StoreC['_A']>((resolve, reject) => {
pipe(
findStore(db, storeName),
O.fold(
() => reject(new Error('Store not found')),
(c) => {
pipe(
c.codec.decode(v),
E.fold(
reject,
() => {
const addRequest = getObjectStore(db, 'readwrite')(storeName).add(v);
addRequest.addEventListener('success', () => resolve(v));
handleRequestError(addRequest, reject);
}
)
);
(store) => {
const addRequest = getObjectStore(db, 'readwrite')(storeName).add(store.codec.encode(v));
addRequest.addEventListener('success', () => resolve(v));
handleRequestError(addRequest, reject);
}
)
);
}),
handlePromiseError,
);

export const put = <A>(
db: DatabaseInfo,
export const put = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
) => (v: A): TE.TaskEither<IndexedDbError, A> =>
) => (v: StoreC['_A']): TE.TaskEither<IndexedDbError, StoreC['_A']> =>
TE.tryCatch(
() => new Promise<A>((resolve, reject) => {
() => new Promise<StoreC['_A']>((resolve, reject) => {
pipe(
findStore(db, storeName),
O.fold(
() => reject(new Error('Store not found')),
(c) => {
pipe(
c.codec.decode(v),
E.fold(
reject,
(item: A) => {
const updateRequest = getObjectStore(db, 'readwrite')(storeName).put(item);
updateRequest.addEventListener('success', () => resolve(v));
handleRequestError(updateRequest, reject);
}
)
);
(store) => {
const updateRequest = getObjectStore(db, 'readwrite')(storeName).put(store.codec.encode(v));
updateRequest.addEventListener('success', () => resolve(v));
handleRequestError(updateRequest, reject);
}
)
);
}),
handlePromiseError,
);

export const getAll = <A>(
db: DatabaseInfo,
export const getAll = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
) =>
TE.tryCatch<IndexedDbError, A[]>(
() => new Promise<A[]>((resolve, reject) => {
TE.tryCatch<IndexedDbError, Array<StoreC['_A']>>(
() => new Promise<Array<StoreC['_A']>>((resolve, reject) => {
const objectStore = pipe(
storeName,
getObjectStore(db, 'readonly')
Expand Down Expand Up @@ -149,12 +134,12 @@ export const getAll = <A>(
handlePromiseError,
);

export const get = <A>(
db: DatabaseInfo,
export const get = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
) => (v: IDBValidKey): TE.TaskEither<IndexedDbError, A> =>
) => (v: IDBValidKey): TE.TaskEither<IndexedDbError, StoreC['_A']> =>
TE.tryCatch(
() => new Promise<A>((resolve, reject) => {
() => new Promise<StoreC['_A']>((resolve, reject) => {
const objectStore = pipe(
storeName,
getObjectStore(db, 'readonly')
Expand Down Expand Up @@ -184,8 +169,8 @@ export const get = <A>(
);


export const remove = (
db: DatabaseInfo,
export const remove = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
) => (v: IDBValidKey): TE.TaskEither<IndexedDbError, boolean> =>
TE.tryCatch(
Expand All @@ -197,8 +182,8 @@ export const remove = (
handlePromiseError,
);

export const clearStore = (
db: DatabaseInfo,
export const clearStore = <StoreC extends t.Mixed>(
db: DatabaseInfo<StoreC>,
storeName: string,
): TE.TaskEither<IndexedDbError, boolean> =>
TE.tryCatch(
Expand Down
13 changes: 7 additions & 6 deletions test/database.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ const userC = t.type({
id: t.number,
name: t.string
});
type UserC = typeof userC;
type User = t.TypeOf<UserC>;

type User = t.TypeOf<typeof userC>;
const schema: DBSchema = {
const schema: DBSchema<UserC> = {
version: 1,
stores: {
'users': {
Expand All @@ -42,7 +43,7 @@ describe('IndexedDb - Tests', () => {
// Insert
const iUser: User = { id: 1, name: 'James' };
await pipe(
db ? insert<User>(db, 'users')(iUser) : dbErrorTe,
db ? insert<UserC>(db, 'users')(iUser) : dbErrorTe,
TE.match(
fail,
(v) => expect(v.name).toEqual(iUser.name),
Expand All @@ -52,7 +53,7 @@ describe('IndexedDb - Tests', () => {
// Update
const uUser: User = { id: 1, name: 'Jimmy' };
await pipe(
db ? put<User>(db, 'users')(uUser) : dbErrorTe,
db ? put<UserC>(db, 'users')(uUser) : dbErrorTe,
TE.match(
fail,
(v: User) => expect(v.name).toEqual(uUser.name),
Expand All @@ -61,7 +62,7 @@ describe('IndexedDb - Tests', () => {

// Get All
await pipe(
db ? getAll<User>(db, 'users') : dbErrorTe,
db ? getAll<UserC>(db, 'users') : dbErrorTe,
TE.match(
fail,
(rows) => {
Expand All @@ -78,7 +79,7 @@ describe('IndexedDb - Tests', () => {

// Get
await pipe(
db ? get<User>(db, 'users')(1) : dbErrorTe,
db ? get<UserC>(db, 'users')(1) : dbErrorTe,
TE.match(
fail,
(record) => {
Expand Down
Loading