* Initializes and configures the Fastify server, including database connection, * authentication, CORS settings, cron jobs, error handling, and routes. * * @returns {Promise } A promise that resolves to the configured Fastify server instance.
()
| 47 | * @returns {Promise<FastifyInstance>} A promise that resolves to the configured Fastify server instance. |
| 48 | */ |
| 49 | async function buildServer() { |
| 50 | // Create a new Fastify server instance with pretty print logging enabled. |
| 51 | const server = Fastify({ |
| 52 | logger: { |
| 53 | transport: { |
| 54 | target: "pino-pretty", |
| 55 | }, |
| 56 | }, |
| 57 | }).withTypeProvider<TypeBoxTypeProvider>(); |
| 58 | |
| 59 | try { |
| 60 | // Connect to the database using the TypeORM plugin. |
| 61 | await server.register(dbConn, { connection: PostgresDataSource }); |
| 62 | } catch (err) { |
| 63 | // Log and exit if the database connection fails. |
| 64 | console.log("Error connecting to database"); |
| 65 | console.log(err); |
| 66 | process.exit(1); |
| 67 | } |
| 68 | |
| 69 | // server.setErrorHandler(async (error, request, reply) => { |
| 70 | // console.log('Error: ', error); |
| 71 | // Sentry.captureException(error); |
| 72 | // reply.status(500).send({ error: error.message || "Something went wrong" }); |
| 73 | // }); |
| 74 | // Register JWT support for authentication. |
| 75 | // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 76 | server.register(require("@fastify/jwt"), { |
| 77 | secret: process.env.JWT_SECRET, |
| 78 | sign: { |
| 79 | expiresIn: "14d", |
| 80 | }, |
| 81 | }); |
| 82 | |
| 83 | // Register the authentication decorator for the server. |
| 84 | server.decorate("authenticate", async (request, reply) => { |
| 85 | try { |
| 86 | const secret = request.headers["ws-secret"]; |
| 87 | if (!secret) { |
| 88 | await request.jwtVerify(); |
| 89 | return; |
| 90 | } |
| 91 | |
| 92 | if (secret === process.env.WS_SECRET) { |
| 93 | return; |
| 94 | } |
| 95 | |
| 96 | const orm = request.server.orm; |
| 97 | const user = await orm.getRepository(User).findOne({ where: { apikey: secret } }); |
| 98 | if (user) { |
| 99 | request.user = user; |
| 100 | return; |
| 101 | } |
| 102 | |
| 103 | reply.code(401).send({ message: "Unauthorized" }); |
| 104 | } catch (err) { |
| 105 | reply.code(401).send({ message: "Unauthorized" }); |
| 106 | } |
no test coverage detected