Skip to content

Commit e400124

Browse files
committed
Improve load of notes stability
Add note doc validator
1 parent eed0d67 commit e400124

File tree

2 files changed

+44
-9
lines changed

2 files changed

+44
-9
lines changed

src/lib/db/FSNoteDb.ts

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
keys,
3131
getFolderPathname,
3232
generateFolderId,
33+
isNoteValidBySchema,
3334
} from './utils'
3435
import { escapeRegExp, generateId, getHexatrigesimalString } from '../string'
3536
import {
@@ -72,15 +73,22 @@ class FSNoteDb implements NoteDb {
7273
const missingFolderPathnameSet = new Set<string>()
7374
const missingTagNameSet = new Set<string>()
7475
for (const note of notes) {
75-
if (note.trashed) {
76-
continue
77-
}
78-
missingFolderPathnameSet.add(note.folderPathname)
79-
note.tags.forEach((tag) => {
80-
if (this.data!.tagMap[tag] == null) {
81-
missingTagNameSet.add(tag)
76+
try {
77+
if (note.trashed) {
78+
continue
8279
}
83-
})
80+
missingFolderPathnameSet.add(note.folderPathname)
81+
note.tags.forEach((tag) => {
82+
if (this.data!.tagMap[tag] == null) {
83+
missingTagNameSet.add(tag)
84+
}
85+
})
86+
} catch (e) {
87+
console.warn(
88+
`Skipping note file because it is not valid JSON note document`
89+
)
90+
console.log(note)
91+
}
8492
}
8593

8694
if (newStorage) {
@@ -797,7 +805,14 @@ class FSNoteDb implements NoteDb {
797805
const rawDoc = await readFileAsString(
798806
join(this.location, 'notes', noteFileName)
799807
)
800-
notes.push(JSON.parse(rawDoc) as NoteDoc)
808+
const note = JSON.parse(rawDoc) as NoteDoc
809+
if (isNoteValidBySchema(note)) {
810+
notes.push(note)
811+
} else {
812+
console.warn(
813+
`[WARNING] Invalid note found ${noteFileName}. Please check if the file is a valid, non-corrupted note data.`
814+
)
815+
}
801816
} catch (error) {
802817
console.error(error)
803818
}

src/lib/db/utils.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import {
1616
LiteStorageStorageItem,
1717
} from './types'
1818
import { generateId, escapeRegExp } from '../string'
19+
import { isValid, schema } from '../predicates'
20+
import ow from 'ow'
1921

2022
export function values<T>(objectMap: ObjectMap<T>): T[] {
2123
return Object.values(objectMap) as T[]
@@ -260,3 +262,21 @@ export function mapStorageToLiteStorageData(
260262
location: storage.location,
261263
}
262264
}
265+
266+
const noteDocPredicate = schema({
267+
_id: ow.string,
268+
title: ow.string,
269+
content: ow.string,
270+
folderPathname: ow.string,
271+
tags: ow.array.ofType(ow.string),
272+
data: ow.object,
273+
createdAt: ow.string,
274+
updatedAt: ow.string,
275+
archivedAt: ow.optional.string,
276+
trashed: ow.boolean,
277+
_rev: ow.string,
278+
})
279+
280+
export function isNoteValidBySchema(note: NoteDoc) {
281+
return isValid(note, noteDocPredicate)
282+
}

0 commit comments

Comments
 (0)