import http from 'node:http' /** * Appwrite-Nachbau für Tests: die REST-Pfade, die server/services/appwriteAdmin.js benutzt, im * Speicher. Mit schema = { collection: ['attr', ...] } lehnt er unbekannte Attribute ab wie * Appwrite ("Invalid document structure: Unknown attribute"). Dokument-IDs prüft er wie Appwrite * (höchstens 36 Zeichen aus a-z, A-Z, 0-9, Punkt, Bindestrich, Unterstrich, kein Sonderzeichen am * Anfang). failNext({ collection?, method?, status, message?, after? }) lässt die nächste passende Anfrage * mit diesem Status scheitern (Fehlerpfade wie "Appwrite nicht erreichbar" oder "Collection fehlt"); * after = Zahl passender Anfragen, die vorher noch durchgehen (z. B. erst die zweite PATCH scheitert). */ export async function startAppwriteMock({ schema = {} } = {}) { const collections = new Map() let sequence = 0 let pendingFailure = null // Wie Appwrite (Validator UID): 'unique()' ist erlaubt, sonst [A-Za-z0-9][A-Za-z0-9._-]{0,35} const validDocumentId = (id) => id === 'unique()' || (typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,35}$/.test(id)) const invalidDocumentId = [ 400, { message: 'Invalid `documentId` param: UID must contain at most 36 chars. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char', code: 400, type: 'general_argument_invalid', }, ] const docs = (collection) => { if (!collections.has(collection)) collections.set(collection, new Map()) return collections.get(collection) } const stamp = (doc, collection) => { const now = new Date().toISOString() return { $createdAt: now, $updatedAt: now, $collectionId: collection, ...doc, $seq: (sequence += 1) } } const seed = (collection, doc) => { if (!doc?.$id) throw new Error('seed: $id fehlt') docs(collection).set(doc.$id, stamp(doc, collection)) } const unknownAttribute = (collection, data) => { const allowed = schema[collection] if (!allowed) return null return Object.keys(data).find((key) => !key.startsWith('$') && !allowed.includes(key)) || null } const matches = (doc, query) => { const value = doc[query.attribute] switch (query.method) { case 'equal': return query.values.includes(value) case 'greaterThan': return value > query.values[0] case 'lessThan': return value < query.values[0] default: return true } } const list = (collection, rawQueries) => { const queries = rawQueries.map((q) => JSON.parse(q)) const unsupported = queries.find((q) => !['equal', 'greaterThan', 'lessThan', 'orderAsc', 'orderDesc', 'limit'].includes(q.method)) if (unsupported) return [400, { message: `Query ${unsupported.method} wird nicht nachgebaut`, code: 400 }] let result = [...docs(collection).values()].filter((doc) => queries.every((q) => matches(doc, q))) for (const q of queries.filter((q) => q.method === 'orderAsc' || q.method === 'orderDesc')) { const dir = q.method === 'orderAsc' ? 1 : -1 result.sort((a, b) => { const x = a[q.attribute] const y = b[q.attribute] if (x === y) return (a.$seq - b.$seq) * dir return (x > y ? 1 : -1) * dir }) } const limit = queries.find((q) => q.method === 'limit') if (limit) result = result.slice(0, limit.values[0]) return [200, { total: result.length, documents: result.map(publicDoc) }] } const publicDoc = ({ $seq, ...doc }) => doc const readBody = (req) => new Promise((resolve) => { let raw = '' req.on('data', (chunk) => (raw += chunk)) req.on('end', () => resolve(raw ? JSON.parse(raw) : {})) }) const handle = async (req) => { const url = new URL(req.url, 'http://127.0.0.1') const docPath = url.pathname.match(/^\/v1\/databases\/[^/]+\/collections\/([^/]+)\/documents(?:\/([^/]+))?$/) const userPath = url.pathname.match(/^\/v1\/users\/([^/]+)$/) if (userPath && req.method === 'GET') return [200, { $id: userPath[1], passwordUpdate: '' }] // GET /v1/account (requireAppwriteStaff, Ticketsystem-JWT): jwt-admin = Mitarbeiter mit Label admin, // jwt-kunde = angemeldet ohne Label, alles andere 401 wie Appwrite bei einem ungueltigen JWT if (url.pathname === '/v1/account' && req.method === 'GET') { const jwt = req.headers['x-appwrite-jwt'] if (jwt === 'jwt-admin') return [200, { $id: 'u_admin', email: 'kenso@webklar.com', labels: ['admin'] }] if (jwt === 'jwt-kunde') return [200, { $id: 'u_admin', email: 'kenso@webklar.com', labels: [] }] return [401, { message: 'User (role: guests) missing scope (account)', code: 401, type: 'general_unauthorized_scope' }] } if (!docPath) return [404, { message: 'Route not found', code: 404 }] const [, collection, id] = docPath const store = docs(collection) const notFound = [404, { message: 'Document with the requested ID could not be found.', code: 404, type: 'document_not_found' }] // Eingeplanter Fehler (failNext): genau eine passende Anfrage scheitert if ( pendingFailure && (!pendingFailure.collection || pendingFailure.collection === collection) && (!pendingFailure.method || pendingFailure.method === req.method) ) { if (pendingFailure.after > 0) { pendingFailure.after -= 1 } else { const { status, message } = pendingFailure pendingFailure = null return [status, { message: message || `Nachbau: eingeplanter Fehler ${status}`, code: status, type: 'general_server_error' }] } } if (!id && req.method === 'GET') return list(collection, url.searchParams.getAll('queries[]')) if (!id && req.method === 'POST') { const { documentId, data = {} } = await readBody(req) if (!validDocumentId(documentId)) return invalidDocumentId if (store.has(documentId)) { return [409, { message: 'Document with the requested ID already exists.', code: 409, type: 'document_already_exists' }] } const bad = unknownAttribute(collection, data) if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }] const doc = stamp({ ...data, $id: documentId }, collection) store.set(documentId, doc) return [201, publicDoc(doc)] } if (id && req.method === 'GET') return store.has(id) ? [200, publicDoc(store.get(id))] : notFound if (id && req.method === 'PATCH') { if (!store.has(id)) return notFound const { data = {} } = await readBody(req) const bad = unknownAttribute(collection, data) if (bad) return [400, { message: `Invalid document structure: Unknown attribute: "${bad}"`, code: 400 }] const doc = { ...store.get(id), ...data, $updatedAt: new Date().toISOString() } store.set(id, doc) return [200, publicDoc(doc)] } if (id && req.method === 'DELETE') { if (!store.delete(id)) return notFound return [204, null] } return [405, { message: 'Method not allowed', code: 405 }] } const server = http.createServer(async (req, res) => { try { const [status, body] = await handle(req) res.writeHead(status, { 'Content-Type': 'application/json' }) res.end(body === null ? '' : JSON.stringify(body)) } catch (err) { res.writeHead(500, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ message: err.message, code: 500 })) } }) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) return { url: `http://127.0.0.1:${server.address().port}/v1`, docs: (collection) => new Map([...docs(collection)].map(([id, doc]) => [id, publicDoc(doc)])), seed, /** Naechste passende Dokument-Anfrage scheitert mit status (einmalig); after passende Anfragen gehen vorher durch. */ failNext: ({ collection = null, method = null, status = 500, message = '', after = 0 }) => { pendingFailure = { collection, method, status, message, after } }, close: () => new Promise((resolve) => server.close(resolve)), } }