forked from unimatrix/web
21 lines
2.5 KiB
JavaScript
21 lines
2.5 KiB
JavaScript
import {identity} from './auth.mjs';
|
|
import {createResearchSpecialists} from './research-specialists.mjs';
|
|
export function createResearchSpecialistAPI(db,keys,settings={},dependencies={}){
|
|
const authenticate=dependencies.authenticate||(request=>identity(request,db)),roles=createResearchSpecialists(db,keys);
|
|
const reply=(body,status=200)=>Response.json(body,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
|
|
return async request=>{
|
|
const url=new URL(request.url),actor=await authenticate(request);if(!actor)return reply({message:'Sign in first.'},401);
|
|
if(url.pathname!=='/api/items/research-specialist')return reply({message:'Not found'},404);
|
|
if(!db.researchSpecialistsEnabled)return reply({message:'Specialist appointment service unavailable.'},503);
|
|
try{
|
|
if(request.method==='GET'){if([...url.searchParams.keys()].sort().join(',')!=='id,kind')throw TypeError('Choose one organisation.');return reply(await roles.read(actor,{kind:url.searchParams.get('kind'),id:url.searchParams.get('id')}));}
|
|
if(request.method!=='POST')return reply({message:'Method not allowed.'},405);
|
|
if(url.search||request.headers.get('origin')!==new URL(settings.CP_ORIGIN||'https://cp.dunerealms.com').origin)return reply({message:'Origin rejected.'},403);
|
|
if(!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return reply({message:'JSON required.'},415);
|
|
const reader=request.body?.getReader();if(!reader)throw TypeError('Appointment required.');let input;
|
|
try{const chunks=[];let bytes=0;while(true){const{done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>2048){await reader.cancel();return reply({message:'Appointment too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));}finally{reader.releaseLock();}
|
|
if(!input||Array.isArray(input)||Object.keys(input).sort().join(',')!=='confirmed,owner,requestId,revision,userId'||!input.owner||Object.keys(input.owner).sort().join(',')!=='id,kind')throw TypeError('Confirm the complete appointment.');
|
|
return reply(await roles.appoint(actor,input));
|
|
}catch(error){if(error instanceof SyntaxError||error instanceof TypeError)return reply({message:error.message},400);if([403,404,409].includes(error.status))return reply({message:error.message},error.status);if(/^Specialist appointment/.test(error.message))return reply({message:error.message},error.message.endsWith('unavailable.')?503:409);throw error;}
|
|
};
|
|
}
|

Staff