notes API cleanup

This commit is contained in:
nicwands
2026-02-23 14:19:07 -05:00
parent 7a670aab92
commit 9ac9d73b0a
8 changed files with 48 additions and 64 deletions

88
src/main/notesAPI.js Normal file
View File

@@ -0,0 +1,88 @@
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,
}