Spaces:
Build error
Build error
File size: 4,977 Bytes
ef73937 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | import { promises as fs } from 'fs';
import { createRequire } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';
import properLockfile from 'proper-lockfile';
import { config } from '@config/index.js';
const require = createRequire(import.meta.url);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface StoredEntity {
id: string;
createdAt: string;
updatedAt: string;
}
export interface QueryOptions {
limit?: number;
offset?: number;
sortBy?: string;
sortOrder?: 'asc' | 'desc';
filter?: Record<string, unknown>;
}
export class JsonStore<T extends StoredEntity> {
private readonly directory: string;
private readonly lockOptions = {
retries: 5,
retryWait: 100,
realpath: false,
};
constructor(entityName: string) {
this.directory = path.join(config.DATA_DIR, entityName);
}
private getFilePath(id: string): string {
return path.join(this.directory, `${id}.json`);
}
async initialize(): Promise<void> {
await fs.mkdir(this.directory, { recursive: true });
}
private async acquireLock(filePath: string): Promise<() => Promise<void>> {
const release = await properLockfile.lock(filePath, this.lockOptions);
return release;
}
async create(entity: T): Promise<T> {
const filePath = this.getFilePath(entity.id);
const release = await this.acquireLock(filePath);
try {
await fs.writeFile(filePath, JSON.stringify(entity, null, 2), 'utf-8');
return entity;
} finally {
await release();
}
}
async findById(id: string): Promise<T | null> {
const filePath = this.getFilePath(id);
try {
const data = await fs.readFile(filePath, 'utf-8');
return JSON.parse(data) as T;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null;
}
throw error;
}
}
async update(id: string, updates: Partial<T>): Promise<T | null> {
const filePath = this.getFilePath(id);
const release = await this.acquireLock(filePath);
try {
const existing = await this.findById(id);
if (!existing) return null;
const updated: T = {
...existing,
...updates,
id: existing.id,
createdAt: existing.createdAt,
updatedAt: new Date().toISOString(),
} as T;
await fs.writeFile(filePath, JSON.stringify(updated, null, 2), 'utf-8');
return updated;
} finally {
await release();
}
}
async delete(id: string): Promise<boolean> {
const filePath = this.getFilePath(id);
const release = await this.acquireLock(filePath);
try {
await fs.unlink(filePath);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return false;
}
throw error;
} finally {
await release();
}
}
async findAll(options: QueryOptions = {}): Promise<T[]> {
const {
limit = 100,
offset = 0,
sortBy = 'createdAt',
sortOrder = 'desc',
filter = {},
} = options;
const files = await fs.readdir(this.directory);
const jsonFiles = files.filter(f => f.endsWith('.json'));
const entities: T[] = [];
for (const file of jsonFiles) {
const data = await fs.readFile(path.join(this.directory, file), 'utf-8');
const entity = JSON.parse(data) as T;
let matches = true;
for (const [key, value] of Object.entries(filter)) {
if ((entity as Record<string, unknown>)[key] !== value) {
matches = false;
break;
}
}
if (matches) {
entities.push(entity);
}
}
entities.sort((a, b) => {
const aVal = (a as Record<string, unknown>)[sortBy];
const bVal = (b as Record<string, unknown>)[sortBy];
if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;
if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;
return 0;
});
return entities.slice(offset, offset + limit);
}
async count(filter: Record<string, unknown> = {}): Promise<number> {
const files = await fs.readdir(this.directory);
let count = 0;
for (const file of files) {
if (!file.endsWith('.json')) continue;
const data = await fs.readFile(path.join(this.directory, file), 'utf-8');
const entity = JSON.parse(data) as T;
let matches = true;
for (const [key, value] of Object.entries(filter)) {
if ((entity as Record<string, unknown>)[key] !== value) {
matches = false;
break;
}
}
if (matches) count++;
}
return count;
}
async exists(id: string): Promise<boolean> {
try {
await fs.access(this.getFilePath(id));
return true;
} catch {
return false;
}
}
async findOne(filter: Record<string, unknown>): Promise<T | null> {
const entities = await this.findAll({ filter, limit: 1 });
return entities[0] || null;
}
} |