89 lines
2.1 KiB
JavaScript
89 lines
2.1 KiB
JavaScript
import { app } from 'electron'
|
|
import fs from 'fs'
|
|
import { join, relative, dirname } from 'path'
|
|
|
|
const BASE_DIR = join(app.getPath('userData'), 'notes-storage')
|
|
export const ensureBaseDir = () => {
|
|
if (!fs.existsSync(BASE_DIR)) {
|
|
fs.mkdirSync(BASE_DIR, { recursive: true })
|
|
}
|
|
}
|
|
|
|
const sanitizeRelativePath = (relativePath) => {
|
|
const resolved = join(BASE_DIR, relativePath)
|
|
if (!resolved.startsWith(BASE_DIR)) {
|
|
throw new Error('Invalid path')
|
|
}
|
|
return resolved
|
|
}
|
|
|
|
const readAllNotesRecursive = (dir = BASE_DIR, base = BASE_DIR) => {
|
|
const entries = fs.readdirSync(dir, { withFileTypes: true })
|
|
let results = []
|
|
|
|
for (const entry of entries) {
|
|
const fullPath = join(dir, entry.name)
|
|
|
|
if (entry.isDirectory()) {
|
|
results = results.concat(readAllNotesRecursive(fullPath, base))
|
|
}
|
|
|
|
if (entry.isFile() && entry.name.endsWith('.md')) {
|
|
const content = fs.readFileSync(fullPath, 'utf-8')
|
|
|
|
results.push({
|
|
name: entry.name,
|
|
path: relative(base, fullPath),
|
|
content,
|
|
})
|
|
}
|
|
}
|
|
|
|
return results
|
|
}
|
|
|
|
const createNote = (relativePath, content = '') => {
|
|
const fullPath = sanitizeRelativePath(relativePath)
|
|
|
|
fs.mkdirSync(dirname(fullPath), { recursive: true })
|
|
fs.writeFileSync(fullPath, content, 'utf-8')
|
|
|
|
return true
|
|
}
|
|
|
|
const createDirectory = (relativePath) => {
|
|
const fullPath = sanitizeRelativePath(relativePath)
|
|
fs.mkdirSync(fullPath, { recursive: true })
|
|
return true
|
|
}
|
|
|
|
const readNote = (relativePath) => {
|
|
const fullPath = sanitizeRelativePath(relativePath)
|
|
|
|
if (!fs.existsSync(fullPath)) {
|
|
createNote(relativePath)
|
|
}
|
|
|
|
return fs.readFileSync(fullPath, 'utf-8')
|
|
}
|
|
|
|
const updateNote = (relativePath, content) => {
|
|
const fullPath = sanitizeRelativePath(relativePath)
|
|
|
|
if (!fs.existsSync(fullPath)) {
|
|
throw new Error('Note does not exist')
|
|
}
|
|
|
|
fs.writeFileSync(fullPath, content, 'utf-8')
|
|
|
|
return true
|
|
}
|
|
|
|
export default {
|
|
readAllNotesRecursive,
|
|
createNote,
|
|
createDirectory,
|
|
readNote,
|
|
updateNote,
|
|
}
|