bend_puzzle/server/json-repository.js
2026-07-31 12:54:46 +09:00

18 lines
920 B
JavaScript

'use strict';
function createJsonRepository({fsp,crypto,processId=process.pid}={}){
if(!fsp?.readFile||!fsp?.writeFile||!fsp?.rename||!crypto?.randomBytes)throw new TypeError('Filesystem and crypto adapters are required');
const read=async(file,{missing=null}={})=>{
try{return JSON.parse(await fsp.readFile(file,'utf8'))}
catch(error){if(error.code==='ENOENT'&&missing!==undefined)return typeof missing==='function'?missing():missing;throw error}
};
const write=async(file,value)=>{
const temporary=`${file}.${processId}.${crypto.randomBytes(6).toString('hex')}.tmp`;
await fsp.writeFile(temporary,JSON.stringify(value),{encoding:'utf8',mode:0o600});
await fsp.rename(temporary,file);
};
const remove=async file=>fsp.unlink(file).catch(error=>{if(error.code!=='ENOENT')throw error});
return Object.freeze({read,write,remove});
}
module.exports=Object.freeze({createJsonRepository});