wip
This commit is contained in:
2
apps/server/.env-template
Normal file
2
apps/server/.env-template
Normal file
@@ -0,0 +1,2 @@
|
||||
NODE_ENV="development"
|
||||
DATABASE_URL="file:../db/dev.db"
|
||||
9
apps/server/.prettierrc
Normal file
9
apps/server/.prettierrc
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"plugins": ["prettier-plugin-svelte"],
|
||||
"pluginSearchDirs": ["."],
|
||||
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
|
||||
}
|
||||
0
apps/server/db/.gitkeep
Normal file
0
apps/server/db/.gitkeep
Normal file
56
apps/server/package.json
Normal file
56
apps/server/package.json
Normal file
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"name": "server",
|
||||
"description": "Coolify's Fastify API",
|
||||
"license": "Apache-2.0",
|
||||
"scripts": {
|
||||
"build": "rimraf ../../build && tsc --outDir ../../build",
|
||||
"dev": "tsx watch --clear-screen=false src",
|
||||
"lint": "prettier --plugin-search-dir . --check . && eslint .",
|
||||
"format": "prettier --plugin-search-dir . --write .",
|
||||
"test-dev": "start-server-and-test 'tsx src/server' http-get://localhost:2022 'tsx src/client'",
|
||||
"test-start": "start-server-and-test 'node dist/server' http-get://localhost:2022 'node dist/client'",
|
||||
"db:generate": "prisma generate",
|
||||
"db:push": "prisma db push && prisma generate",
|
||||
"db:seed": "prisma db seed",
|
||||
"db:studio": "prisma studio",
|
||||
"db:migrate": "DATABASE_URL=file:../db/migration.db prisma migrate dev --skip-seed --name"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsonwebtoken": "8.5.1",
|
||||
"@fastify/autoload": "5.6.0",
|
||||
"@fastify/cors": "8.2.0",
|
||||
"@fastify/env": "4.1.0",
|
||||
"@fastify/jwt": "6.5.0",
|
||||
"@fastify/static": "6.6.0",
|
||||
"@fastify/websocket": "7.1.1",
|
||||
"@prisma/client": "4.6.1",
|
||||
"@trpc/client": "10.1.0",
|
||||
"@trpc/server": "10.1.0",
|
||||
"abort-controller": "3.0.0",
|
||||
"fastify": "4.10.2",
|
||||
"fastify-plugin": "4.4.0",
|
||||
"node-fetch": "3.3.0",
|
||||
"prisma": "4.6.1",
|
||||
"superjson": "1.11.0",
|
||||
"tslib": "2.4.1",
|
||||
"ws": "8.11.0",
|
||||
"zod": "3.19.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "18.11.9",
|
||||
"@types/node-fetch": "2.6.2",
|
||||
"@types/ws": "8.5.3",
|
||||
"npm-run-all": "4.1.5",
|
||||
"rimraf": "3.0.2",
|
||||
"start-server-and-test": "1.14.0",
|
||||
"tsx": "3.12.1",
|
||||
"typescript": "4.9.3",
|
||||
"wait-port": "1.0.4"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "restricted"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "Category" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"name" TEXT NOT NULL,
|
||||
"budget" INTEGER NOT NULL,
|
||||
"customIcon" TEXT,
|
||||
"period" TEXT NOT NULL DEFAULT 'month',
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Transaction" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"amount" INTEGER NOT NULL,
|
||||
"description" TEXT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
"categoryId" INTEGER NOT NULL,
|
||||
CONSTRAINT "Transaction_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "Category" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
|
||||
);
|
||||
3
apps/server/prisma/migrations/migration_lock.toml
Normal file
3
apps/server/prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "sqlite"
|
||||
11
apps/server/prisma/schema.prisma
Normal file
11
apps/server/prisma/schema.prisma
Normal file
@@ -0,0 +1,11 @@
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
7
apps/server/src/config/index.ts
Normal file
7
apps/server/src/config/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { ServerOptions } from '../server';
|
||||
|
||||
export const serverConfig: ServerOptions = {
|
||||
dev: false,
|
||||
port: 2022,
|
||||
prefix: '/trpc'
|
||||
};
|
||||
15
apps/server/src/env.js
Normal file
15
apps/server/src/env.js
Normal file
@@ -0,0 +1,15 @@
|
||||
const { z } = require('zod');
|
||||
|
||||
/*eslint sort-keys: "error"*/
|
||||
const envSchema = z.object({
|
||||
NODE_ENV: z.enum(['development', 'test', 'production']),
|
||||
COOLIFY_SECRET_KEY: z.string()
|
||||
});
|
||||
|
||||
const env = envSchema.safeParse(process.env);
|
||||
|
||||
if (!env.success) {
|
||||
console.error('❌ Invalid environment variables:', JSON.stringify(env.error.format(), null, 4));
|
||||
process.exit(1);
|
||||
}
|
||||
module.exports.env = env.data;
|
||||
7
apps/server/src/index.ts
Normal file
7
apps/server/src/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { serverConfig } from './config';
|
||||
import { createServer } from './server';
|
||||
|
||||
const server = createServer(serverConfig);
|
||||
|
||||
server.start();
|
||||
|
||||
21
apps/server/src/prisma.ts
Normal file
21
apps/server/src/prisma.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Instantiates a single instance PrismaClient and save it on the global object.
|
||||
* @link https://www.prisma.io/docs/support/help-articles/nextjs-prisma-client-dev-practices
|
||||
*/
|
||||
import { env } from './env';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prismaGlobal = global as typeof global & {
|
||||
prisma?: PrismaClient;
|
||||
};
|
||||
|
||||
export const prisma: PrismaClient =
|
||||
prismaGlobal.prisma ||
|
||||
new PrismaClient({
|
||||
log:
|
||||
env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
if (env.NODE_ENV !== 'production') {
|
||||
prismaGlobal.prisma = prisma;
|
||||
}
|
||||
19
apps/server/src/router/context.ts
Normal file
19
apps/server/src/router/context.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { inferAsyncReturnType } from '@trpc/server';
|
||||
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { env } from '../env';
|
||||
export interface User {
|
||||
name: string | string[];
|
||||
}
|
||||
|
||||
export function createContext({ req, res }: CreateFastifyContextOptions) {
|
||||
const token = req.headers.authorization;
|
||||
if (token) {
|
||||
const user = jwt.verify(token, env.COOLIFY_SECRET_KEY);
|
||||
|
||||
console.log(user);
|
||||
}
|
||||
return { req, res };
|
||||
}
|
||||
|
||||
export type Context = inferAsyncReturnType<typeof createContext>;
|
||||
8
apps/server/src/router/index.ts
Normal file
8
apps/server/src/router/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { apiRouter } from './routers/api';
|
||||
import { router } from './trpc';
|
||||
|
||||
export const appRouter = router({
|
||||
api: apiRouter,
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
18
apps/server/src/router/routers/api.ts
Normal file
18
apps/server/src/router/routers/api.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
// import { z } from 'zod';
|
||||
import { publicProcedure, router } from '../trpc';
|
||||
// import { prisma } from '../../prisma';
|
||||
import { TRPCError } from '@trpc/server';
|
||||
|
||||
export const apiRouter = router({
|
||||
getConnection: publicProcedure.query(async () => {
|
||||
try {
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'An unexpected error occurred, please try again later.',
|
||||
cause: error
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
13
apps/server/src/router/trpc.ts
Normal file
13
apps/server/src/router/trpc.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { initTRPC } from '@trpc/server';
|
||||
import superjson from 'superjson';
|
||||
import { Context } from './context';
|
||||
|
||||
const t = initTRPC.context<Context>().create({
|
||||
transformer: superjson,
|
||||
errorFormatter({ shape }) {
|
||||
return shape;
|
||||
},
|
||||
});
|
||||
|
||||
export const router = t.router;
|
||||
export const publicProcedure = t.procedure;
|
||||
58
apps/server/src/server.ts
Normal file
58
apps/server/src/server.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
|
||||
import fastify from 'fastify';
|
||||
import { appRouter } from './router';
|
||||
import { createContext } from './router/context';
|
||||
import cors from '@fastify/cors';
|
||||
import * as path from 'node:path';
|
||||
import serve from '@fastify/static';
|
||||
// import { prisma } from './prisma';
|
||||
|
||||
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,
|
||||
trpcOptions: { router: appRouter, createContext }
|
||||
});
|
||||
// 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');
|
||||
});
|
||||
}
|
||||
server.get('/api', async () => {
|
||||
return { status: 'ok' };
|
||||
});
|
||||
const stop = () => server.close();
|
||||
const start = async () => {
|
||||
try {
|
||||
await server.listen({ host: '0.0.0.0', port });
|
||||
console.log('Server is listening on port', port);
|
||||
} catch (err) {
|
||||
server.log.error(err);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
return { server, start, stop };
|
||||
}
|
||||
43
apps/server/tsconfig.json
Normal file
43
apps/server/tsconfig.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"include": ["src", "server/src/config.ts"],
|
||||
"exclude": ["node_modules"],
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "esnext",
|
||||
"outDir": "dist",
|
||||
|
||||
// [ Basics ]
|
||||
"strict": true,
|
||||
"checkJs": true,
|
||||
"sourceMap": true,
|
||||
"importHelpers": true,
|
||||
"removeComments": true,
|
||||
// "rootDir": "./",
|
||||
// "declaration": true,
|
||||
// "declarationMap": true,
|
||||
// "declarationDir": "types",
|
||||
|
||||
// [ Additional Checks ]
|
||||
"noUnusedLocals": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitOverride": true,
|
||||
"allowUnreachableCode": false,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
|
||||
// [ Module Resolution ]
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
|
||||
// [ Advanced ]
|
||||
// "skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
|
||||
// [ Build ]
|
||||
"listFiles": false,
|
||||
"listEmittedFiles": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user