Skip to content

Commit

Permalink
✨ feat(app): add idb package, update indedex-db service
Browse files Browse the repository at this point in the history
  • Loading branch information
drackp2m committed Nov 21, 2024
1 parent 3fee6c3 commit f001d96
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 109 deletions.
8 changes: 5 additions & 3 deletions apps/app-e2e/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import path from 'node:path';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';

import { FlatCompat } from '@eslint/eslintrc';
import js from '@eslint/js';

import baseConfig from '../../eslint.config.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
Expand Down
13 changes: 5 additions & 8 deletions apps/app/src/app/layout/main/main.layout.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NgTemplateOutlet } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, inject, signal } from '@angular/core';
import { Router, RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { SwUpdate } from '@angular/service-worker';
Expand Down Expand Up @@ -55,8 +56,10 @@ export default class MainLayout implements OnInit {
this.getPings.set(data.data.getPings);
}
},
error: (error) => {
this.getPings.set(error.message);
error: (error: unknown) => {
const typedError = error as HttpErrorResponse;

console.error(typedError.message);
},
});
}
Expand All @@ -78,8 +81,6 @@ export default class MainLayout implements OnInit {
if (this.swUpdate.isEnabled) {
this.swUpdate.versionUpdates.subscribe({
next: (version) => {
console.log({ version });

switch (version.type) {
case 'VERSION_DETECTED':
console.log('New version detected. Downloading...');
Expand All @@ -99,10 +100,6 @@ export default class MainLayout implements OnInit {
}
},
});

// const haveUpdates = await this.swUpdate.checkForUpdate();

// console.log({ haveUpdates });
}
}
}
99 changes: 26 additions & 73 deletions apps/app/src/app/service/indexed-db/indexed-db.service.ts
Original file line number Diff line number Diff line change
@@ -1,112 +1,65 @@
import { Injectable } from '@angular/core';
import { DBSchema, IDBPDatabase, openDB } from 'idb';

import { LocalStorageKey } from './definition/indexed-db-key.enum';

interface KeyValueStoreSchema extends DBSchema {
KeyValueStore: {
key: LocalStorageKey;
value: unknown;
};
}

@Injectable({
providedIn: 'root',
})
export class IndexedDBService {
private dbName = 'PlaySetOnline';
private storeName = 'KeyValueStore';
private dbVersion = 1;
private dbPromise: Promise<IDBDatabase>;
private readonly dbName = 'PlaySetOnline';
private readonly storeName = 'KeyValueStore';
private readonly dbVersion = 1;
private readonly dbPromise: Promise<IDBPDatabase<KeyValueStoreSchema>>;

constructor() {
this.dbPromise = this.initDB();
}

async setItem<T>(key: LocalStorageKey, data: T): Promise<void> {
async setItem<T>(key: LocalStorageKey, value: T): Promise<void> {
const db = await this.dbPromise;

return new Promise((resolve, reject) => {
const transaction = db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.put({ key, value: data });

request.onsuccess = () => {
resolve();
};

request.onerror = (event) => {
reject((event.target as IDBRequest).error);
};
});
await db.put(this.storeName, { key, value });
}

async getItem<T>(key: LocalStorageKey): Promise<T | undefined> {
const db = await this.dbPromise;

return new Promise((resolve, reject) => {
const transaction = db.transaction([this.storeName], 'readonly');
const store = transaction.objectStore(this.storeName);
const request = store.get(key);
const item = await db.get(this.storeName, key);

request.onsuccess = (event) => {
const result = (event.target as IDBRequest).result;
resolve(result ? (result.value as T) : undefined);
};
const typedItem = item as { value: T } | undefined;

request.onerror = (event) => {
reject((event.target as IDBRequest).error);
};
});
return typedItem?.value;
}

async deleteItem(key: LocalStorageKey): Promise<void> {
const db = await this.dbPromise;

return new Promise((resolve, reject) => {
const transaction = db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.delete(key);

request.onsuccess = () => {
resolve();
};

request.onerror = (event) => {
reject((event.target as IDBRequest).error);
};
});
await db.delete(this.storeName, key);
}

async clearStore(): Promise<void> {
const db = await this.dbPromise;

return new Promise((resolve, reject) => {
const transaction = db.transaction([this.storeName], 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.clear();

request.onsuccess = () => {
resolve();
};

request.onerror = (event) => {
reject((event.target as IDBRequest).error);
};
});
await db.clear(this.storeName);
}

private initDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.dbVersion);
private initDB(): Promise<IDBPDatabase<KeyValueStoreSchema>> {
const storeName = this.storeName;

request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName, { keyPath: 'key' });
return openDB<KeyValueStoreSchema>(this.dbName, this.dbVersion, {
upgrade(db) {
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'key' });
}
};

request.onsuccess = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
resolve(db);
};

request.onerror = (event) => {
reject((event.target as IDBOpenDBRequest).error);
};
},
});
}
}
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"codegen",
"commitlint",
"devkit",
"IDBP",
"mikro",
"nestjs",
"ngneat",
Expand Down
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ services:
MIKRO_ORM_CLI_TS_CONFIG_PATH: apps/api/tsconfig.app.json
MIKRO_ORM_CLI_ALWAYS_ALLOW_TS: 1
MIKRO_ORM_CLI_USE_TS_NODE: 1
NODE_TLS_REJECT_UNAUTHORIZED: 0
PATH: $PATH:/usr/src/app/node_modules/.bin
TZ: UTC
depends_on:
Expand Down
22 changes: 14 additions & 8 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

import nx from '@nx/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import eslintPluginImport from 'eslint-plugin-import';
Expand All @@ -6,6 +9,11 @@ import rxjs from 'eslint-plugin-rxjs-updated';
import unusedImports from 'eslint-plugin-unused-imports';
import globals from 'globals';

import eslintErrorsToWarnings from './tools/helpers/eslint-errors-to-warnings.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export default [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
Expand All @@ -14,12 +22,10 @@ export default [
plugins: {
prettier,
'@nx': nx,
rxjs: rxjs,
rxjs,
import: eslintPluginImport,
'unused-imports': unusedImports,
},
},
{
ignores: ['**/dist', 'node_modules', 'libs/api-definitions/src/lib/apollo/operations.ts'],
},
{
Expand Down Expand Up @@ -73,6 +79,9 @@ export default [
parser: tsParser,
ecmaVersion: 2023,
sourceType: 'module',
parserOptions: {
project: join(__dirname, './tsconfig.base.json'),
},
},
settings: {
'import/ignore': ['node_modules'],
Expand All @@ -84,15 +93,12 @@ export default [
},
},
rules: {
// ...Object.fromEntries(
// Object.entries(sonarjs.configs.recommended.rules).map(([ruleName, ruleValue]) => {
// return [`${ruleName}`, ruleValue.replace('error', 'warn')];
// }),
// ),
// ...eslintErrorsToWarnings(sonarjs.configs.recommended.rules),
// 'sonarjs/todo-tag': 'off',
// 'sonarjs/fixme-tag': 'off',
// 'sonarjs/unused-import': 'off',
// 'sonarjs/pseudo-random': 'warn',
...eslintErrorsToWarnings(rxjs.configs.recommended.rules),
'unused-imports/no-unused-imports': 'warn',
'no-unused-private-class-members': 'warn',
'@typescript-eslint/no-unused-vars': [
Expand Down
8 changes: 1 addition & 7 deletions libs/api-sdk/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import parser from 'jsonc-eslint-parser';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import { FlatCompat } from '@eslint/eslintrc';
import baseConfig from '../../eslint.config.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import baseConfig from '../../eslint.config.mjs';

export default [
...baseConfig,
Expand Down
11 changes: 9 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"cookie-parser": "1.4.7",
"graphql": "16.9.0",
"graphql-subscriptions": "3.0.0",
"idb": "^8.0.0",
"mikro-orm": "6.4.0",
"ms": "2.1.3",
"node-cache": "5.1.2",
Expand Down
12 changes: 12 additions & 0 deletions tools/helpers/eslint-errors-to-warnings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default function eslintErrorsToWarnings(rules) {
return Object.fromEntries(
Object.entries(rules).map(([ruleName, ruleValue]) => {
ruleValue =
typeof ruleValue === 'string'
? ruleValue?.replace('error', 'warn')
: ruleValue[0]?.replace('error', 'warn');

return [ruleName, ruleValue];
}),
);
}
14 changes: 7 additions & 7 deletions tools/helpers/patch-nx-source-map-paths.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const path = require('path');
import { relative } from 'node:path';

/*
* Temporary workaround for debugging Node applications being built with webpack and Nx.
* See: https://github.com/nrwl/nx/issues/14708#issuecomment-1457996600
*/
module.exports = function patchNxSourceMapPaths(config) {
config.output.devtoolModuleFilenameTemplate = function (info) {
const rel = path.relative(process.cwd(), info.absoluteResourcePath);
return `webpack:///./${rel}`;
};
config.output.devtoolModuleFilenameTemplate = function (info) {
const rel = relative(process.cwd(), info.absoluteResourcePath);
return `webpack:///./${rel}`;
};

config.devtool = 'source-map';
config.devtool = 'source-map';

return config;
return config;
};

0 comments on commit f001d96

Please sign in to comment.