import { localDataSource } from '../LocalDataSource'; import type { ILocalDataSource } from '@/data/datasources/interfaces'; export interface IPostCacheRepository { save(id: string, data: any): Promise; get(id: string): Promise; getAll(): Promise; delete(id: string): Promise; } export class PostCacheRepository implements IPostCacheRepository { constructor(private dataSource: ILocalDataSource = localDataSource) {} async save(id: string, data: any): Promise { await this.dataSource.enqueueWrite(async () => { await this.dataSource.run( `INSERT OR REPLACE INTO posts_cache (id, data, updatedAt) VALUES (?, ?, ?)`, [String(id), JSON.stringify(data), new Date().toISOString()] ); }); } async get(id: string): Promise { const r = await this.dataSource.getFirst<{ data: string }>( `SELECT data FROM posts_cache WHERE id = ?`, [String(id)] ); return r?.data ? JSON.parse(r.data) : null; } async getAll(): Promise { const rows = await this.dataSource.query<{ data: string }>( `SELECT data FROM posts_cache ORDER BY updatedAt DESC` ); return rows.map(r => JSON.parse(r.data)); } async delete(id: string): Promise { await this.dataSource.enqueueWrite(async () => { await this.dataSource.run(`DELETE FROM posts_cache WHERE id = ?`, [String(id)]); }); } } export const postCacheRepository = new PostCacheRepository();