Skip to content

Commit

Permalink
Add indexedDB
Browse files Browse the repository at this point in the history
  • Loading branch information
congmul committed Jul 11, 2024
1 parent b9e5fb0 commit b2a746b
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 6 deletions.
19 changes: 14 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import { useLocalStorageState } from './utils';
import { Theme } from './utils/theme.cont';
import IndexedDB from './utils/indexedDB';

function App() {
const [ content, setContent ] = useState<string | undefined>();
Expand All @@ -17,11 +18,21 @@ function App() {
const [ themeState ] = useLocalStorageState('theme', Theme.LIGHT);
const bodyElRef = useRef(document.querySelector('body'));
const [ currentTheme, setCurrentTheme ] = useState<string>(themeState);
const indexedDBIns = new IndexedDB('editor-db', 'editorContent', 'value');

useEffect(() => {
// Check IndexedDB to grab API Specification
// if there is no exsiting spec.
setContent(JSON.stringify(petStoreAPISpec, null, 2));
// Check IndexedDB to grab API Specification
indexedDBIns.loadContentFromDB()
.then(async (res) => {
if(!res){
// if there is no exsiting spec, use pet store api spec.
await indexedDBIns.saveContentToDB(petStoreAPISpec);
setContent(JSON.stringify(petStoreAPISpec, null, 2));
}else{
// if it exists, display it on Editor.
setContent(JSON.stringify(res, null, 2));
}
})
}, [])
useEffect(() => {
// Check Theme
Expand All @@ -48,8 +59,6 @@ function App() {
<Editor content={content} setContent={setContent} currentTheme={currentTheme}/>
<div className={`p-2 vh-100`}
style={{overflowY: "auto"}}>
<>{console.log(currentTheme)}</>
{/* {currentTheme === Theme.DARK && <ThemeComponent />} */}
<SwaggerUI spec={content} />
</div>
</ReactSplitPane>
Expand Down
7 changes: 6 additions & 1 deletion src/components/Editor/components/MonacoEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Editor from '@monaco-editor/react';
import Spinner from 'react-bootstrap/Spinner';
import { SpectralLinter, applyErrorMarkers } from '../../../utils';
import { Theme, EditorThemeData } from '../../../utils/theme.cont';
import IndexedDB from '../../../utils/indexedDB';

interface MonacoEditorTypes {
editorRef: any
Expand All @@ -12,6 +13,8 @@ interface MonacoEditorTypes {
}
const MonacoEditor:React.FC<MonacoEditorTypes> = ({ editorRef, monacoRef, content, setContent, currentTheme }) => {
const { lintScan } = SpectralLinter();
const indexedDBIns = new IndexedDB('editor-db', 'editorContent', 'content');

function handleEditorWillMount(monaco:any){
monaco.editor.defineTheme(Theme.LIGHT, EditorThemeData[Theme.LIGHT]);
monaco.editor.defineTheme(Theme.DARK, EditorThemeData[Theme.DARK]);
Expand All @@ -25,9 +28,11 @@ const MonacoEditor:React.FC<MonacoEditorTypes> = ({ editorRef, monacoRef, conten
applyErrorMarkers(res, editorRef.current, monacoRef.current)
});
}
function onChange() {
async function onChange() {
const editorValue = editorRef.current?.getValue();
setContent(editorValue);
// Store value into indexedDB
indexedDBIns.saveContentToDB(JSON.parse(editorValue))
}
return(<>
{
Expand Down
65 changes: 65 additions & 0 deletions src/utils/indexedDB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
export default class IndexedDB {
dbName:string;
objectStoreName:string;
storeId: string;
request:any;
constructor(dbName:string, objectStoreName:string, storeId:string) {
this.dbName = dbName;
this.objectStoreName = objectStoreName;
this.storeId = storeId;

// Open DB
this.request = indexedDB.open(dbName, 1);
// Create ObjectStore
this.request.onupgradeneeded = () => {
const db = this.request.result;
if (!db.objectStoreNames.contains(this.objectStoreName)) {
db.createObjectStore(this.objectStoreName, { keyPath: 'id' });
}
};
this.request.onerror = (event:any) => {
console.log(`Error opening IndexedDB: ${event}`);
};
}

saveContentToDB(value: Record<string, any>) {
return new Promise((resolve) => {
const db = this.request.result;
const transaction = db.transaction([this.objectStoreName], 'readwrite');
const store = transaction.objectStore(this.objectStoreName);
store.put({ id: this.storeId, value });

transaction.oncomplete = () => {
resolve('Content saved to IndexedDB');
};
});
}

loadContentFromDB() {
return new Promise((resolve, reject) => {
this.request.onsuccess = () => {
const db = this.request.result;
const transaction = db.transaction([this.objectStoreName], 'readonly');
const store = transaction.objectStore(this.objectStoreName);
const getRequest = store.get('content');
getRequest.onsuccess = () => {
if (getRequest.result) {
resolve(getRequest.result.value);
}else{
resolve(undefined)
}
};

getRequest.onerror = (event:any) => {
console.error('Error getting content from IndexedDB:', event);
reject({status:"error", message: `'Error getting content from IndexedDB: ${event}` });
};
};

this.request.onerror = (event:any) => {
console.error('Error opening IndexedDB:', event);
reject({status:"error", message: `Error opening IndexedDB: ${event}` });
};
})
}
}

0 comments on commit b2a746b

Please sign in to comment.