Added Ts.ED

This commit is contained in:
2022-09-04 21:00:45 +02:00
parent d0b69d7ae1
commit f4162f7f06
45 changed files with 4046 additions and 0 deletions

13
backend/.barrelsby.json Normal file
View File

@@ -0,0 +1,13 @@
{
"directory": [
"./src/controllers/rest",
"./src/datasources",
"./src/resolvers"
],
"exclude": [
"__mock__",
"__mocks__",
".spec.ts"
],
"delete": true
}

4
backend/.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules
Dockerfile
.env.local
.env.development

57
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,57 @@
### Node template
.DS_Store
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules
.npmrc
*.log
# Typings
typings/
# Typescript
src/**/*.js
src/**/*.js.map
test/**/*.js
test/**/*.js.map
# Test
/.tmp
/.nyc_output
# IDE
.vscode
.idea
# Project
/public
/dist
#env
.env.local
.env.development

47
backend/Dockerfile Normal file
View File

@@ -0,0 +1,47 @@
###############################################################################
###############################################################################
## _______ _____ ______ _____ ##
## |__ __/ ____| ____| __ \ ##
## | | | (___ | |__ | | | | ##
## | | \___ \| __| | | | | ##
## | | ____) | |____| |__| | ##
## |_| |_____/|______|_____/ ##
## ##
## description : Dockerfile for TsED Application ##
## author : TsED team ##
## date : 2022-03-05 ##
## version : 2.0 ##
## ##
###############################################################################
###############################################################################
ARG NODE_VERSION=16.13.1
FROM node:${NODE_VERSION}-alpine as build
WORKDIR /opt
COPY package.json yarn.lock tsconfig.json tsconfig.compile.json .barrelsby.json ./
RUN yarn install --pure-lockfile
COPY ./src ./src
RUN yarn build
FROM node:${NODE_VERSION}-alpine as runtime
ENV WORKDIR /opt
WORKDIR $WORKDIR
RUN apk update && apk add build-base git curl
RUN npm install -g pm2
COPY --from=build /opt .
RUN yarn install --pure-lockfile --production
COPY ./prisma ./prisma
COPY processes.config.js .
EXPOSE 8081
ENV PORT 8081
ENV NODE_ENV production
CMD ["pm2-runtime", "start", "processes.config.js", "--env", "production"]

67
backend/README.md Normal file
View File

@@ -0,0 +1,67 @@
<p style="text-align: center" align="center">
<a href="https://tsed.io" target="_blank"><img src="https://tsed.io/tsed-og.png" width="200" alt="Ts.ED logo"/></a>
</p>
<div align="center">
<h1>Ts.ED - backend</h1>
<br />
<div align="center">
<a href="https://cli.tsed.io/">Website</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://cli.tsed.io/getting-started.html">Getting started</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://api.tsed.io/rest/slack/tsedio/tsed">Slack</a>
<span>&nbsp;&nbsp;•&nbsp;&nbsp;</span>
<a href="https://twitter.com/TsED_io">Twitter</a>
</div>
<hr />
</div>
> An awesome project based on Ts.ED framework
## Getting started
> **Important!** Ts.ED requires Node >= 14, Express >= 4 and TypeScript >= 4.
```batch
# install dependencies
$ install
# serve
$ start
# build for production
$ build
$ start:prod
```
## Docker
```
# build docker image
docker compose build
# start docker image
docker compose up
```
## Barrelsby
This project uses [barrelsby](https://www.npmjs.com/package/barrelsby) to generate index files to import the controllers.
Edit `.barreslby.json` to customize it:
```json
{
"directory": [
"./src/controllers/rest",
"./src/controllers/pages"
],
"exclude": [
"__mock__",
"__mocks__",
".spec.ts"
],
"delete": true
}
```

View File

@@ -0,0 +1,14 @@
version: '3.5'
services:
server:
build:
context: .
dockerfile: ./Dockerfile
args:
- http_proxy
- https_proxy
- no_proxy
image: backend/server:latest
ports:
- "8081:8081"

78
backend/package.json Normal file
View File

@@ -0,0 +1,78 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"scripts": {
"build": "yarn run barrels && tsc --project tsconfig.compile.json",
"barrels": "barrelsby --config .barrelsby.json",
"start": "yarn run barrels && tsnd --inspect --ignore-watch node_modules --respawn --transpile-only -r tsconfig-paths/register src/index.ts",
"start:prod": "cross-env NODE_ENV=production node dist/index.js",
"prisma:migrate": "npx prisma migrate dev --name init",
"prisma:generate": "npx prisma generate"
},
"dependencies": {
"@tsed/ajv": "^6.129.0",
"@tsed/common": "^6.129.0",
"@tsed/core": "^6.129.0",
"@tsed/di": "^6.129.0",
"@tsed/engines": "^6.129.0",
"@tsed/exceptions": "^6.129.0",
"@tsed/json-mapper": "^6.129.0",
"@tsed/logger": "^6.2.2",
"@tsed/logger-file": "^6.2.2",
"@tsed/platform-cache": "^6.129.0",
"@tsed/platform-exceptions": "^6.129.0",
"@tsed/platform-express": "^6.129.0",
"@tsed/platform-log-middleware": "^6.129.0",
"@tsed/platform-middlewares": "^6.129.0",
"@tsed/platform-params": "^6.129.0",
"@tsed/platform-response-filter": "^6.129.0",
"@tsed/platform-views": "^6.129.0",
"@tsed/schema": "^6.129.0",
"@tsed/socketio": "^6.129.0",
"@tsed/typegraphql": "^6.129.0",
"ajv": "^8.11.0",
"apollo-datasource": "^3.3.1",
"apollo-datasource-rest": "^3.5.1",
"apollo-server-core": "^3.6.2",
"apollo-server-express": "2.25.2",
"barrelsby": "^2.4.0",
"body-parser": "^1.20.0",
"class-validator": "^0.13.2",
"compression": "^1.7.4",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"cross-env": "^7.0.3",
"dotenv": "^16.0.2",
"dotenv-expand": "^9.0.0",
"dotenv-flow": "^3.2.0",
"express": "^4.18.1",
"graphql": "^15.7.2",
"method-override": "^3.0.0",
"socket.io": "^4.5.2",
"type-graphql": "^1.1.1"
},
"devDependencies": {
"@tsed/cli-plugin-prisma": "3.26.0",
"@tsed/cli-plugin-typegraphql": "3.26.0",
"@types/compression": "^1.7.2",
"@types/cookie-parser": "^1.4.3",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/method-override": "^0.0.32",
"@types/multer": "^1.4.7",
"@types/node": "^18.7.14",
"@types/validator": "^13.7.6",
"apollo-server-testing": "^2.25.3",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"tsconfig-paths": "^4.1.0",
"tslib": "^2.4.0",
"typescript": "^4.8.2"
},
"tsed": {
"packageManager": "yarn",
"convention": "default",
"architecture": "default"
}
}

View File

@@ -0,0 +1,21 @@
// 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 = "postgresql"
url = env("DATABASE_URL")
}
generator tsed {
provider = "tsed-prisma"
}
model User {
id Int @default(autoincrement()) @id
email String @unique
name String?
}

View File

@@ -0,0 +1,23 @@
'use strict'
const path = require('path')
const defaultLogFile = path.join(__dirname, '/logs/project-server.log')
module.exports = {
'apps': [
{
name: "api",
'script': `${process.env.WORKDIR}/dist/index.js`,
'cwd': process.env.WORKDIR,
node_args: process.env.NODE_ARGS || "--max_old_space_size=1800",
exec_mode: "cluster",
instances: process.env.NODE_ENV === "test" ? 1 : process.env.NB_INSTANCES || 2,
autorestart: true,
max_memory_restart: process.env.MAX_MEMORY_RESTART || "750M",
'out_file': defaultLogFile,
'error_file': defaultLogFile,
'merge_logs': true,
'kill_timeout': 30000,
}
]
}

54
backend/src/Server.ts Normal file
View File

@@ -0,0 +1,54 @@
import {join} from "path";
import {Configuration, Inject} from "@tsed/di";
import {PlatformApplication} from "@tsed/common";
import "@tsed/platform-express"; // /!\ keep this import
import bodyParser from "body-parser";
import compress from "compression";
import cookieParser from "cookie-parser";
import methodOverride from "method-override";
import cors from "cors";
import "@tsed/ajv";
import "@tsed/typegraphql";
import "./datasources/index";
import "./resolvers/index";
import {config} from "./config/index";
import * as rest from "./controllers/rest/index";
@Configuration({
...config,
acceptMimes: ["application/json"],
httpPort: process.env.PORT || 8083,
httpsPort: false, // CHANGE
componentsScan: false,
mount: {
"/rest": [
...Object.values(rest)
]
},
middlewares: [
cors(),
cookieParser(),
compress({}),
methodOverride(),
bodyParser.json(),
bodyParser.urlencoded({
extended: true
})
],
views: {
root: join(process.cwd(), "../views"),
extensions: {
ejs: "ejs"
}
},
exclude: [
"**/*.spec.ts"
]
})
export class Server {
@Inject()
protected app: PlatformApplication;
@Configuration()
protected settings: Configuration;
}

View File

@@ -0,0 +1,7 @@
import dotenv from "dotenv"
export const envs = {
...process.env,
...dotenv.config().parsed
};
export const isProduction = process.env.NODE_ENV === "production";

View File

@@ -0,0 +1,18 @@
import {readFileSync} from "fs";
import {envs} from "./envs/index";
import loggerConfig from "./logger/index";
const pkg = JSON.parse(readFileSync("./package.json", {encoding: "utf8"}));
export const config: Partial<TsED.Configuration> = {
version: pkg.version,
envs,
logger: loggerConfig,
graphql: {
default: {
path: "/graphql",
buildSchemaOptions: {
}
}
},
// additional shared configuration
};

View File

@@ -0,0 +1,24 @@
import {$log, PlatformLoggerSettings} from "@tsed/common";
import {isProduction} from "../envs/index";
if (isProduction) {
$log.appenders.set("stdout", {
type: "stdout",
levels: ["info", "debug"],
layout: {
type: "json"
}
});
$log.appenders.set("stderr", {
levels: ["trace", "fatal", "error", "warn"],
type: "stderr",
layout: {
type: "json"
}
});
}
export default <PlatformLoggerSettings> {
disableRoutesSummary: isProduction
};

View File

@@ -0,0 +1,10 @@
import {Controller} from "@tsed/di";
import {Get} from "@tsed/schema";
@Controller("/hello-world")
export class HelloWorldController {
@Get("/")
get() {
return "hello";
}
}

View File

@@ -0,0 +1,18 @@
import {DataSourceService} from "@tsed/typegraphql";
import {RESTDataSource} from "apollo-datasource-rest";
@DataSourceService()
export class MyDataSource extends RESTDataSource {
constructor() {
super();
this.baseURL = "http://localhost:8001";
}
willSendRequest(request: any) {
request.headers.set("Authorization", this.context.token);
}
getMyData(id: string) {
return this.get(`/rest/calendars/${id}`);
}
}

View File

@@ -0,0 +1 @@
export * from "./MyDataSource";

18
backend/src/index.ts Normal file
View File

@@ -0,0 +1,18 @@
import {$log} from "@tsed/common";
import { PlatformExpress } from "@tsed/platform-express";
import {Server} from "./Server";
async function bootstrap() {
try {
const platform = await PlatformExpress.bootstrap(Server);
await platform.listen();
process.on("SIGINT", () => {
platform.stop();
});
} catch (error) {
$log.error({event: "SERVER_BOOTSTRAP_ERROR", message: error.message, stack: error.stack});
}
}
bootstrap();

View File

@@ -0,0 +1,3 @@
export * from "./recipes/Recipe";
export * from "./recipes/RecipeNotFoundError";
export * from "./recipes/RecipeResolver";

View File

@@ -0,0 +1,27 @@
import {Field, ID, ObjectType} from "type-graphql";
@ObjectType({description: "Object representing cooking recipe"})
export class Recipe {
@Field((type) => ID)
id: string;
@Field()
title: string;
@Field({nullable: true})
description?: string;
@Field()
creationDate: Date;
@Field((type) => [String])
ingredients: string[];
constructor(options: Partial<Recipe> = {}) {
options.id && (this.id = options.id);
options.title && (this.title = options.title);
options.description && (this.description = options.description);
options.creationDate && (this.creationDate = options.creationDate);
options.ingredients && (this.ingredients = options.ingredients);
}
}

View File

@@ -0,0 +1,7 @@
import {NotFound} from "@tsed/exceptions";
export class RecipeNotFoundError extends NotFound {
constructor(private id: string) {
super("Recipe not found");
}
}

View File

@@ -0,0 +1,26 @@
import {ResolverService} from "@tsed/typegraphql";
import {Arg, Query} from "type-graphql";
import {RecipeService} from "../../services/RecipeService";
import {Recipe} from "./Recipe";
import {RecipeNotFoundError} from "./RecipeNotFoundError";
@ResolverService(Recipe)
export class RecipeResolver {
constructor(private recipeService: RecipeService) {}
@Query((returns) => Recipe)
async recipe(@Arg("id") id: string) {
const recipe = await this.recipeService.findById(id);
if (recipe === undefined) {
throw new RecipeNotFoundError(id);
}
return recipe;
}
@Query((returns) => [Recipe], {description: "Get all the recipes from around the world "})
async recipes(): Promise<Recipe[]> {
return this.recipeService.findAll({});
}
}

View File

@@ -0,0 +1,13 @@
import {Injectable} from "@tsed/di";
import {Recipe} from "../resolvers";
@Injectable()
export class RecipeService {
async findById(id: string) {
return new Recipe({id})
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async findAll(query: any) {
return []
}
}

View File

@@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"outDir": "./dist",
"moduleResolution": "node",
"declaration": true,
"noResolve": false,
"preserveConstEnums": true,
"sourceMap": true,
"noEmit": false,
"emitDeclarationOnly": false,
"inlineSources": true
}
}

39
backend/tsconfig.json Normal file
View File

@@ -0,0 +1,39 @@
{
"compilerOptions": {
"baseUrl": ".",
"sourceRoot": "src",
"module": "commonjs",
"target": "esnext",
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"moduleResolution": "node",
"isolatedModules": false,
"suppressImplicitAnyIndexErrors": false,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"allowSyntheticDefaultImports": true,
"importHelpers": true,
"newLine": "LF",
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"lib": [
"es7",
"dom",
"ESNext.AsyncIterable"
],
"typeRoots": [
"./node_modules/@types"
]
},
"include": [
"src"
],
"linterOptions": {
"exclude": []
}
}

3442
backend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff