1
0
mirror of https://github.com/BoostIo/Boostnote synced 2025-12-13 17:56:25 +00:00

renew init method

This commit is contained in:
Dick Choi
2016-08-27 14:01:31 +09:00
parent 87cfc8f1de
commit db3a4d0f01
4 changed files with 134 additions and 100 deletions

View File

@@ -1,8 +1,7 @@
'use strict'
const _ = require('lodash')
const sander = require('sander')
const path = require('path')
const resolveStorageData = require('./resolveStorageData')
const resolveStorageNotes = require('./resolveStorageNotes')
/**
* @return {Object} all storages and notes
* ```
@@ -11,6 +10,11 @@ const path = require('path')
* notes: [...]
* }
* ```
*
* This method deals with 3 patterns.
* 1. v1
* 2. legacy
* 3. empty directory
*/
function init () {
let fetchStorages = function () {
@@ -19,67 +23,38 @@ function init () {
rawStorages = JSON.parse(window.localStorage.getItem('storages'))
if (!_.isArray(rawStorages)) throw new Error('Cached data is not valid.')
} catch (e) {
console.error(e)
console.warn('Failed to parse cached data from localStorage', e)
rawStorages = []
window.localStorage.setItem('storages', JSON.stringify(rawStorages))
}
return Promise.all(rawStorages
.map(function assignFoldersToStorage (rawStorage) {
let data
let boostnoteJSONPath = path.join(rawStorage.path, 'boostnote.json')
try {
data = JSON.parse(sander.readFileSync(boostnoteJSONPath))
if (!_.isArray(data.folders)) throw new Error('folders should be an array.')
rawStorage.folders = data.folders
} catch (err) {
if (err.code === 'ENOENT') {
console.warn('boostnote.json file doesn\'t exist the given path')
} else {
console.error(err)
}
rawStorage.folders = []
}
return Promise.resolve(rawStorage)
}))
.map(resolveStorageData))
}
let fetchNotes = function (storages) {
let notes = []
storages
.forEach((storage) => {
storage.folders.forEach((folder) => {
let dataPath = path.join(storage.path, folder.key, 'data.json')
let data
try {
data = JSON.parse(sander.readFileSync(dataPath))
if (!_.isArray(data.notes)) throw new Error('notes should be an array.')
} catch (e) {
// Remove folder if fetching failed.
console.error('Failed to load data: %s', dataPath)
storage.folders = storage.folders.filter((_folder) => _folder.key !== folder.key)
data = {notes: []}
}
data.notes.forEach((note) => {
note.storage = storage.key
note.folder = folder.key
notes.push(note)
})
})
let findNotesFromEachStorage = storages
.map(resolveStorageNotes)
return Promise.all(findNotesFromEachStorage)
.then(function concatNoteGroup (noteGroups) {
return noteGroups.reduce(function (sum, group) {
return sum.concat(group)
}, [])
})
.then(function returnData (notes) {
return {
storages,
notes
}
})
return Promise.resolve({
storages,
notes
})
}
return Promise.resolve(fetchStorages())
.then((storages) => {
storages = storages.filter((storage) => {
if (!_.isObject(storage)) return false
return true
})
return storages
.filter((storage) => {
if (!_.isObject(storage)) return false
return true
})
})
.then(fetchNotes)
}