61 lines
1.8 KiB
TypeScript
61 lines
1.8 KiB
TypeScript
import { readdir } from "node:fs/promises"
|
|
import { join } from "node:path"
|
|
|
|
const DICTIONARIES_PATH = join(process.cwd(), "data", "dictionaries")
|
|
|
|
export const sanitizeDictionaryName = (name: string) => {
|
|
return name.replace(/[^a-zA-Z0-9_]/g, "_")
|
|
}
|
|
|
|
export const createDictionary = async (name: string, content: string): Promise<string> => {
|
|
const dictionaryName = sanitizeDictionaryName(name)
|
|
const path = join(DICTIONARIES_PATH, `${dictionaryName}.txt`)
|
|
const file = Bun.file(path)
|
|
|
|
if (await file.exists()) {
|
|
throw new Error(`Dictionary "${dictionaryName}" already exists`)
|
|
}
|
|
|
|
await file.write(content)
|
|
return dictionaryName
|
|
}
|
|
|
|
export const readDictionary = async (name: string): Promise<string> => {
|
|
const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`)
|
|
const file = Bun.file(path)
|
|
|
|
if (!(await file.exists())) {
|
|
throw new Error(`Dictionary "${name === "" || name === undefined ? "undefined" : name}" does not exist`)
|
|
}
|
|
return Bun.file(path).text()
|
|
}
|
|
|
|
export const listDictionaries = async (): Promise<string[]> => {
|
|
const files = await readdir(DICTIONARIES_PATH, { recursive: true })
|
|
|
|
return files.map((file) => file.replace(".txt", ""))
|
|
}
|
|
|
|
export const updateDictionary = async (name: string, content: string): Promise<void> => {
|
|
const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`)
|
|
|
|
const file = Bun.file(path)
|
|
|
|
if (!(await file.exists())) {
|
|
throw new Error(`Dictionary "${name}" does not exist`)
|
|
}
|
|
|
|
await file.write(content)
|
|
}
|
|
|
|
export const deleteDictionary = async (name: string): Promise<void> => {
|
|
const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`)
|
|
|
|
const file = Bun.file(path)
|
|
if (!(await file.exists())) {
|
|
throw new Error(`Dictionary "${name}" does not exist`)
|
|
}
|
|
|
|
await file.delete()
|
|
}
|