UNPKG

query-2jz

Version:

Query-2jz: A GraphQL alternative with faster performance and simpler use

140 lines (115 loc) 3.35 kB
import { FastifyInstance, FastifyPluginOptions } from 'fastify'; import { Qryn, QrynConfig, QrynModel } from '../index'; /** * Fastify Adapter for Qryn */ export class QrynFastifyAdapter { private qryn: Qryn; constructor(config: QrynConfig, models: QrynModel[] = []) { this.qryn = new Qryn(config, models); } /** * Initialize the adapter */ async initialize(): Promise<void> { await this.qryn.initialize(); } /** * Get Qryn instance */ getQryn(): Qryn { return this.qryn; } /** * Register Fastify plugin */ async register(fastify: FastifyInstance, options: FastifyPluginOptions): Promise<void> { // Health check fastify.get('/health', async (request, reply) => { const stats = this.qryn.getStats(); return { status: 'healthy', timestamp: new Date().toISOString(), ...stats }; }); // Query endpoint fastify.get('/api/qryn/:model', async (request, reply) => { const { model } = request.params as { model: string }; const query = this.parseQueryParams(request.query as any); const result = await this.qryn.query(query, model); if (result.meta?.etag) { reply.header('ETag', result.meta.etag); } if (result.meta?.lastModified) { reply.header('Last-Modified', result.meta.lastModified); } reply.header('Cache-Control', 'public, max-age=300'); return result; }); // Mutation endpoint fastify.post('/api/qryn/:model', async (request, reply) => { const { model } = request.params as { model: string }; const mutation = request.body as any; if (!mutation.operation) { reply.code(400); return { error: 'Invalid mutation', message: 'Operation is required' }; } const result = await this.qryn.mutate(mutation, model); reply.header('Cache-Control', 'no-cache'); return result; }); // Statistics endpoint fastify.get('/api/qryn/stats', async (request, reply) => { return this.qryn.getStats(); }); } private parseQueryParams(queryParams: any): any { const query: any = {}; if (queryParams.select) { try { query.select = JSON.parse(queryParams.select); } catch { query.select = {}; } } if (queryParams.where) { try { query.where = JSON.parse(queryParams.where); } catch { query.where = {}; } } if (queryParams.orderBy) { try { query.orderBy = JSON.parse(queryParams.orderBy); } catch { query.orderBy = {}; } } if (queryParams.limit) { query.limit = parseInt(queryParams.limit); } if (queryParams.offset) { query.offset = parseInt(queryParams.offset); } if (queryParams.live === 'true') { query.live = true; } return query; } } /** * Fastify plugin factory */ export function createQrynPlugin(config: QrynConfig, models: QrynModel[] = []) { const adapter = new QrynFastifyAdapter(config, models); return { adapter, plugin: adapter.register.bind(adapter), initialize: () => adapter.initialize() }; }