76 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-12-12 08:44:23 +01:00
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import fastify from 'fastify';
2022-12-12 14:48:56 +01:00
import { appRouter } from './trpc';
import { createContext } from './trpc/context';
2022-12-12 08:44:23 +01:00
import cors from '@fastify/cors';
import * as path from 'node:path';
import serve from '@fastify/static';
2022-12-12 14:48:56 +01:00
import autoLoad from '@fastify/autoload';
2022-12-12 08:44:23 +01:00
// import { prisma } from './prisma';
2022-12-21 15:06:33 +01:00
import Graceful from '@ladjs/graceful';
import { scheduler } from './scheduler';
2022-12-12 08:44:23 +01:00
const isDev = process.env['NODE_ENV'] === 'development';
export interface ServerOptions {
dev?: boolean;
port?: number;
prefix?: string;
}
export function createServer(opts: ServerOptions) {
const dev = opts.dev ?? true;
const port = opts.port ?? 3000;
const prefix = opts.prefix ?? '/trpc';
const server = fastify({ logger: dev, trustProxy: true });
server.register(cors);
server.register(fastifyTRPCPlugin, {
prefix,
2022-12-12 14:48:56 +01:00
trpcOptions: {
router: appRouter,
createContext,
onError({ error, type, path, input, ctx, req }) {
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
}
}
2022-12-12 08:44:23 +01:00
});
// Serve static files in production. Static files are generated by `yarn build` in the client folder by SvelteKit.
if (!isDev) {
server.register(serve, {
root: path.join(__dirname, './public'),
preCompressed: true
});
server.setNotFoundHandler(async function (request, reply) {
if (request.raw.url && request.raw.url.startsWith('/api')) {
return reply.status(404).send({
success: false
});
}
return reply.status(200).sendFile('index.html');
});
}
2022-12-12 14:48:56 +01:00
server.register(autoLoad, {
dir: path.join(__dirname, 'api'),
options: { prefix: '/api' }
2022-12-12 08:44:23 +01:00
});
2022-12-12 14:48:56 +01:00
2022-12-12 08:44:23 +01:00
const stop = () => server.close();
const start = async () => {
try {
await server.listen({ host: '0.0.0.0', port });
2022-12-12 14:48:56 +01:00
console.log('Coolify server is listening on port', port, 'at 0.0.0.0 🚀');
2022-12-21 15:06:33 +01:00
const graceful = new Graceful({ brees: [scheduler] });
graceful.listen();
scheduler.run('worker');
2022-12-12 08:44:23 +01:00
} catch (err) {
server.log.error(err);
process.exit(1);
}
};
return { server, start, stop };
}