Tests: Stripe- und Appwrite-Nachbau im Testprozess
getStripe() nutzt in Tests über STRIPE_API_BASE den Nachbau auf 127.0.0.1; in Produktion ist der Wert leer und nichts ändert sich. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
877fde7a6f
commit
54defb75c4
6 files changed
+271
-1
No files matched your search
@@ -0,0 +1,133 @@
|
||||
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").
|
||||
*/
|
||||
export async function startAppwriteMock({ schema = {} } = {}) {
|
||||
const collections = new Map()
|
||||
let sequence = 0
|
||||
|
||||
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: '' }]
|
||||
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' }]
|
||||
|
||||
if (!id && req.method === 'GET') return list(collection, url.searchParams.getAll('queries[]'))
|
||||
if (!id && req.method === 'POST') {
|
||||
const { documentId, data = {} } = await readBody(req)
|
||||
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,
|
||||
close: () => new Promise((resolve) => server.close(resolve)),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user