'use strict'; /* POST /alliances. Found an alliance: needs Peering office >= 1 on one of the founder's POPs; the founder becomes * leader. Size cap = 10 + 2 * best Peering office level at this moment (rules.allianceCap), stored. */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); const { cleanText } = require('../text'); const A = require('../alliances'); const NAME_RE = /^[\p{L}\p{N}][\p{L}\p{N} _.'-]*$/u; module.exports = function allianceCreate(ctx, { userId, worldId, name, tag }) { const { db, now } = ctx; const S = A.S; const op = A.operatorOf(db, userId, worldId); if (A.membership(db, op.id)) throw new GameError('already_in_alliance', { allianceId: A.membership(db, op.id).alliance_id }); const lvl = A.peeringLevel(db, op.id); if (lvl < S.minPeeringLevel) throw new GameError('peering_office_required', { have: lvl, need: S.minPeeringLevel }); name = cleanText(name); tag = cleanText(tag); const errors = []; const len = [...name].length; if (len < S.nameLen[0] || len > S.nameLen[1] || !NAME_RE.test(name)) errors.push({ path: 'name', message: 'must be ' + S.nameLen[0] + '-' + S.nameLen[1] + ' letters, digits, spaces or _ . \' -' }); if (!/^[A-Za-z0-9]+$/.test(tag) || tag.length < S.tagLen[0] || tag.length > S.tagLen[1]) errors.push({ path: 'tag', message: 'must be ' + S.tagLen[0] + '-' + S.tagLen[1] + ' letters or digits' }); if (errors.length) throw new GameError('validation_failed', { errors }); if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND name = ?', op.world_id, name)) throw new GameError('alliance_name_taken'); if (db.get('SELECT 1 AS x FROM alliances WHERE world_id = ? AND tag = ?', op.world_id, tag)) throw new GameError('alliance_tag_taken'); const cap = R.allianceCap(lvl); const r = db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)', op.world_id, name, tag, cap, op.id, now); const id = Number(r.lastInsertRowid); A.addMember(db, id, op.id, 'leader', now); return { allianceId: id, name, tag, sizeCap: cap, role: 'leader' }; };