{"version":3,"file":"fastify.cjs","names":[],"sources":["../src/adapter/fastify/plugin.ts"],"sourcesContent":["import type { ClientContract } from '@zenstackhq/orm';\nimport type { SchemaDef } from '@zenstackhq/orm/schema';\nimport type { FastifyPluginCallback, FastifyReply, FastifyRequest } from 'fastify';\nimport fp from 'fastify-plugin';\nimport { logInternalError, type CommonAdapterOptions } from '../common';\n\n/**\n * Fastify plugin options\n */\nexport interface FastifyPluginOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {\n    /**\n     * Url prefix, e.g.: /api\n     */\n    prefix: string;\n\n    /**\n     * Callback for getting a ZenStackClient for the given request\n     */\n    getClient: (\n        request: FastifyRequest,\n        reply: FastifyReply,\n    ) => ClientContract<Schema> | Promise<ClientContract<Schema>>;\n}\n\n/**\n * Fastify plugin for handling CRUD requests.\n */\nconst pluginHandler: FastifyPluginCallback<FastifyPluginOptions<SchemaDef>> = (fastify, options, done) => {\n    const prefix = options.prefix ?? '';\n\n    fastify.all(`${prefix}/*`, async (request, reply) => {\n        const client = await options.getClient(request, reply);\n        if (!client) {\n            reply.status(500).send({ message: 'unable to get ZenStackClient from request context' });\n            return reply;\n        }\n\n        try {\n            const response = await options.apiHandler.handleRequest({\n                method: request.method,\n                path: (request.params as any)['*'],\n                query: request.query as Record<string, string | string[]>,\n                requestBody: request.body,\n                client,\n            });\n            reply.status(response.status).send(response.body);\n        } catch (err) {\n            logInternalError(options.apiHandler.log, err);\n            reply.status(500).send({ message: `An internal server error occurred` });\n        }\n\n        return reply;\n    });\n\n    done();\n};\n\nconst plugin = fp(pluginHandler);\n\nexport { plugin as ZenStackFastifyPlugin };\n"],"mappings":";;;;;;;;;AA2BA,MAAM,iBAAyE,SAAS,SAAS,SAAS;CACtG,MAAM,SAAS,QAAQ,UAAU;AAEjC,SAAQ,IAAI,GAAG,OAAO,KAAK,OAAO,SAAS,UAAU;EACjD,MAAM,SAAS,MAAM,QAAQ,UAAU,SAAS,MAAM;AACtD,MAAI,CAAC,QAAQ;AACT,SAAM,OAAO,IAAI,CAAC,KAAK,EAAE,SAAS,qDAAqD,CAAC;AACxF,UAAO;;AAGX,MAAI;GACA,MAAM,WAAW,MAAM,QAAQ,WAAW,cAAc;IACpD,QAAQ,QAAQ;IAChB,MAAO,QAAQ,OAAe;IAC9B,OAAO,QAAQ;IACf,aAAa,QAAQ;IACrB;IACH,CAAC;AACF,SAAM,OAAO,SAAS,OAAO,CAAC,KAAK,SAAS,KAAK;WAC5C,KAAK;AACV,kBAAA,iBAAiB,QAAQ,WAAW,KAAK,IAAI;AAC7C,SAAM,OAAO,IAAI,CAAC,KAAK,EAAE,SAAS,qCAAqC,CAAC;;AAG5E,SAAO;GACT;AAEF,OAAM;;AAGV,MAAM,UAAA,GAAA,eAAA,SAAY,cAAc"}