web/website/node/public-clans.mjs
2026-11-21 20:22:37 +01:00

16 lines
2.2 KiB
JavaScript

import {isClandestineInstitution} from './clandestine-identity.mjs';
import {readOrganisationNetwork} from './organisation-network.mjs';
import {readClanDeed,publicDeed,DeedError} from './clan-deeds.mjs';
import {clanTitles} from '../control-panel/public/clan-titles.mjs';
import {clanEmblemUrl} from '../control-panel/clan-emblems.mjs';
export function createPublicClans(db){return async request=>{
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store','Access-Control-Allow-Origin':'*','X-Content-Type-Options':'nosniff'}}),url=new URL(request.url),tag=url.pathname.split('/').at(-1);
if(!['GET','HEAD'].includes(request.method))return reply({message:'Method not allowed.'},405);
if(!/^[A-Z0-9]{2,6}$/i.test(tag)||url.search)return reply({message:'Clan not found.'},404);
const row=await db.prepare('SELECT id FROM site_clans WHERE tag=? AND active=1').bind(tag.toUpperCase()).first();if(!row||isClandestineInstitution('clan',row.id))return reply({message:'Clan not found.'},404);
try{const deed=await readClanDeed(db,row.id,{includePolitics:true}),clan=deed.clan,count=await db.prepare('SELECT COUNT(*) total FROM site_clan_members WHERE clan_id=?').bind(clan.id).first();
const result={clan:{id:clan.id,name:clan.name,tag:clan.tag,description:clan.description,homeWorld:clan.home_world,createdAt:Number(clan.created_at),colors:deed.colors,memberCount:Number(count.total),emblem:clanEmblemUrl(clan.id)},members:deed.candidates.filter(m=>m.clan_id===clan.id).map(m=>({username:m.username,title:m.clan_role==='owner'?clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key}).owner:m.clan_role==='officer'?'Officer':'Member'})),deed:publicDeed(deed),titles:clanTitles({home_world:clan.home_world,charterKind:deed.kind,institution:clan.institution_key})};
if(db.networkLayoutsEnabled)try{result.network={state:'available',...(await readOrganisationNetwork(db,{kind:'clan',id:clan.id})).network,source:{kind:'clan',id:clan.id}};}catch{result.network={state:'unavailable'};}
return request.method==='HEAD'?new Response(null,{headers:{'Cache-Control':'no-store'}}):reply(result);
}catch(error){if(error instanceof DeedError)return reply({message:error.message},error.status);throw error;}
};}