feat(other): backend - mail api for it4c (#231)

* backend - mail api for it4c

Implements an fastify backend service with an email service.
This allows to send us emails received via contact form on the website.

* optional telephone

* missing text delimiter

* start command and correct build method to classicjs

* deploy for backend & adjust README.md

* debug deploy [1]

* debug deploy [2]

* debug deploy [3]

* debug deploy [4]

* debug deploy [5]

* finish deploy script

* watch when running npm run dev

* fix format validation

* debug sendmail[1]

* debug sendmail[2]

* debug sendmail[3]

* debug sendmail[4]

* debug sendmail[5]

* env for MAIL_HOST

* referece name in email subject

* fix format string

* eslint

* backend build & lint workflows

* order comments

* unit tests

* unit test workflow

* prettier

* alias paths

* fix esm support

* 100% tests

* corrected nodejs version

* use beforeEach to clearAllMocks

This simplifies the code and reduces redundancy

* fix wrong import
This commit is contained in:
Ulf Gebhardt 2025-03-07 10:32:56 +01:00 committed by GitHub
parent 7b6bc03b67
commit 73f51b8bc4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 9966 additions and 7 deletions

View File

@ -4,27 +4,43 @@
SCRIPT_PATH=$(realpath $0)
SCRIPT_DIR=$(dirname $SCRIPT_PATH)
PROJECT_ROOT=$SCRIPT_DIR/../..
DEPLOY_DIR=$1
# by default this will create folders in the project root
DEPLOY_DIR=${1:-test}
BUILD_DIR=$PROJECT_ROOT/docs/.vuepress/dist
# assuming you are already on the right branch
git pull -ff
# Frontend
GIT_REF=$(git rev-parse --short HEAD)
DEPLOY_DIR_REF=$DEPLOY_DIR-$GIT_REF
# Parameter is a proper directory?
## Parameter is a proper directory?
if [ -d "$DEPLOY_DIR_REF" ]; then
return "Directory '$DEPLOY_DIR_REF' does already exist" 2>/dev/null || exit 1
fi
# Build the project
## Build the project
cd $PROJECT_ROOT
rm -R $BUILD_DIR
npm install
npm run build
# Copy files and Sym link
mkdir $DEPLOY_DIR_REF/
cp -r $BUILD_DIR/* $DEPLOY_DIR_REF/
ln -sfn $DEPLOY_DIR_REF $DEPLOY_DIR
## Copy files and Sym link
mkdir "$DEPLOY_DIR_REF/"
cp -r $BUILD_DIR/* "$DEPLOY_DIR_REF/"
ln -sfn "$DEPLOY_DIR_REF" $DEPLOY_DIR
# backend
BACKEND_ROOT=$PROJECT_ROOT/backend
BACKEND_SERVICE=it4c-backend
cd $BACKEND_ROOT
pm2 stop $BACKEND_SERVICE
pm2 delete $BACKEND_SERVICE
npm install
npm run build
pm2 start 'npm run start' --name $BACKEND_SERVICE

View File

@ -0,0 +1,35 @@
name: build
on: push
jobs:
files-changed:
name: Detect File Changes - build
runs-on: ubuntu-latest
outputs:
build: ${{ steps.filter.outputs.build }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
id: filter
with:
filters: |
build:
- '.github/workflows/**/*'
- 'backend/**/*'
build:
if: needs.files-changed.outputs.build == 'true'
name: Build
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.0.3
with:
node-version-file: './.tool-versions'
- name: Install Dependencies & Build Library
run: |
npm install
npm run build
working-directory: ./backend

33
.github/workflows/backend.test.lint.yml vendored Normal file
View File

@ -0,0 +1,33 @@
name: backend:test:lint
on: push
jobs:
files-changed:
name: Detect File Changes - lint
runs-on: ubuntu-latest
outputs:
lint: ${{ steps.filter.outputs.lint }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
id: filter
with:
filters: |
lint:
- '.github/workflows/**/*'
- 'backend/**/*'
lint:
if: needs.files-changed.outputs.lint == 'true'
name: Lint
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.0.3
with:
node-version-file: './.tool-versions'
- name: Lint
run: npm install && npm run test:lint:eslint
working-directory: ./backend

35
.github/workflows/backend.test.unit.yml vendored Normal file
View File

@ -0,0 +1,35 @@
name: test:unit
on: push
jobs:
files-changed:
name: Detect File Changes - unit
runs-on: ubuntu-latest
outputs:
unit: ${{ steps.filter.outputs.unit }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
id: filter
with:
filters: |
unit:
- '.github/workflows/**/*'
- 'backend/**/*'
unit:
if: needs.files-changed.outputs.unit == 'true'
name: Unit
needs: files-changed
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.7
- uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.0.3
with:
node-version-file: './.tool-versions'
- name: Install Dependencies & Build Library
run: |
npm install
npm run test:unit
working-directory: ./backend

1
.tool-versions Normal file
View File

@ -0,0 +1 @@
nodejs 20.8.1

View File

@ -83,6 +83,26 @@ vi /etc/nginx/http.d/default.conf
# #access_log $LOG_PATH/nginx-access.hooks.log hooks_log;
# #error_log $LOG_PATH/nginx-error.backend.hook.log warn;
# }
# for the backend install pm2
npm install pm2 -g
# expose the backend service via nginx
vi /etc/nginx/http.d/default.conf
# location /api/ {
# proxy_http_version 1.1;
# proxy_set_header Upgrade $http_upgrade;
# proxy_set_header Connection 'upgrade';
# proxy_set_header X-Forwarded-For $remote_addr;
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header Host $host;
#
# proxy_pass http://127.0.0.1:3000/;
# proxy_redirect off;
#
# #access_log $LOG_PATH/nginx-access.api.log hooks_log;
# #error_log $LOG_PATH/nginx-error.api.log warn;
# }
```
For the github webhook configure the following:

3
backend/.eslintignore Normal file
View File

@ -0,0 +1,3 @@
node_modules/
build/
coverage/

221
backend/.eslintrc.cjs Normal file
View File

@ -0,0 +1,221 @@
// eslint-disable-next-line import/no-commonjs
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
'eslint:recommended',
'plugin:@eslint-community/eslint-comments/recommended',
'plugin:@typescript-eslint/recommended',
'plugin:import/recommended',
'plugin:import/typescript',
// 'plugin:promise/recommended',
'plugin:security/recommended-legacy',
'plugin:react/recommended',
],
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: [
'@typescript-eslint',
'import',
'promise',
'security',
'no-catch-all',
'react',
'react-hooks',
'react-refresh',
],
settings: {
'import/resolver': {
typescript: true,
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
},
react: {
version: '18.2.0',
},
},
rules: {
'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks
'react-hooks/exhaustive-deps': 'warn', // Checks effect dependencies
'react/react-in-jsx-scope': 'off', // Disable requirement for React import
'no-catch-all/no-catch-all': 'error',
'no-console': 'error',
'no-debugger': 'error',
camelcase: 'error',
indent: ['error', 2],
'linebreak-style': ['error', 'unix'],
semi: ['error', 'never'],
// Optional eslint-comments rule
'@eslint-community/eslint-comments/no-unused-disable': 'error',
'@eslint-community/eslint-comments/disable-enable-pair': ['error', { allowWholeFile: true }],
// import
'import/export': 'error',
'import/no-deprecated': 'error',
'import/no-empty-named-blocks': 'error',
'import/no-extraneous-dependencies': 'error',
'import/no-mutable-exports': 'error',
'import/no-unused-modules': 'error',
'import/no-named-as-default': 'error',
'import/no-named-as-default-member': 'error',
'import/no-amd': 'error',
'import/no-commonjs': 'error',
'import/no-import-module-exports': 'error',
'import/no-nodejs-modules': 'off',
'import/unambiguous': 'off', // not compatible with scriptless vue files
'import/default': 'error',
'import/named': 'error',
'import/namespace': 'error',
'import/no-absolute-path': 'error',
'import/no-cycle': 'error',
'import/no-dynamic-require': 'error',
'import/no-internal-modules': 'off',
'import/no-relative-packages': 'error',
'import/no-relative-parent-imports': [
'error',
{
ignore: ['#[src,types,root,components,utils,assets]/*'],
},
],
'import/no-self-import': 'error',
'import/no-unresolved': [
'error',
{
ignore: ['react'],
},
],
'import/no-useless-path-segments': 'error',
'import/no-webpack-loader-syntax': 'error',
'import/consistent-type-specifier-style': 'error',
'import/exports-last': 'off',
'import/extensions': [
'error',
'never',
{
json: 'always',
},
],
'import/first': 'error',
'import/group-exports': 'off',
'import/newline-after-import': 'error',
'import/no-anonymous-default-export': 'off', // todo - consider to enable again
'import/no-default-export': 'off', // incompatible with vite & vike
'import/no-duplicates': 'error',
'import/no-named-default': 'error',
'import/no-namespace': 'error',
'import/no-unassigned-import': [
'error',
{
allow: ['**/*.css'],
},
],
'import/order': [
'error',
{
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index', 'object', 'type'],
'newlines-between': 'always',
alphabetize: {
order: 'asc', // sort in ascending order. Options: ["ignore", "asc", "desc"]
caseInsensitive: true, // ignore case. Options: [true, false]
},
distinctGroup: true,
},
],
'import/prefer-default-export': 'off',
// promise
'promise/catch-or-return': 'error',
'promise/no-return-wrap': 'error',
'promise/param-names': 'error',
'promise/always-return': 'error',
'promise/no-native': 'off',
'promise/no-nesting': 'warn',
'promise/no-promise-in-callback': 'warn',
'promise/no-callback-in-promise': 'warn',
'promise/avoid-new': 'warn',
'promise/no-new-statics': 'error',
'promise/no-return-in-finally': 'warn',
'promise/valid-params': 'warn',
'promise/prefer-await-to-callbacks': 'error',
'promise/no-multiple-resolved': 'error',
},
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json', '**/tsconfig.json'],
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: ['@typescript-eslint'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:@typescript-eslint/strict',
],
rules: {
'@typescript-eslint/consistent-type-imports': 'error',
// allow explicitly defined dangling promises
'@typescript-eslint/no-floating-promises': ['error', { ignoreVoid: true }],
'no-void': ['error', { allowAsStatement: true }],
},
},
{
files: ['!*.json'],
plugins: ['prettier'],
extends: ['plugin:prettier/recommended'],
rules: {
'prettier/prettier': 'error',
},
},
{
files: ['*.json'],
plugins: ['json'],
extends: ['plugin:json/recommended-with-comments'],
},
// {
// files: ['*.{test,spec}.[tj]s'],
// plugins: ['vitest'],
// extends: ['plugin:vitest/all'],
// rules: {
// 'vitest/prefer-lowercase-title': 'off',
// 'vitest/no-hooks': 'off',
// 'vitest/consistent-test-filename': 'off',
// 'vitest/prefer-expect-assertions': [
// 'off',
// {
// onlyFunctionsWithExpectInLoop: true,
// onlyFunctionsWithExpectInCallback: true,
// },
// ],
// 'vitest/prefer-strict-equal': 'off',
// 'vitest/prefer-to-be-falsy': 'off',
// 'vitest/prefer-to-be-truthy': 'off',
// 'vitest/require-hook': [
// 'error',
// {
// allowedFunctionCalls: [
// 'mockClient.setRequestHandler',
// 'setActivePinia',
// 'provideApolloClient',
// ],
// },
// ],
// },
// },
{
files: ['*.yaml', '*.yml'],
parser: 'yaml-eslint-parser',
plugins: ['yml'],
extends: ['plugin:yml/prettier'],
},
],
}

4
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.DS_Store
/node_modules/
/build
/coverage

14
backend/.prettierrc.json Normal file
View File

@ -0,0 +1,14 @@
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"quoteProps": "as-needed",
"jsxSingleQuote": true,
"trailingComma": "all",
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "auto"
}

View File

@ -0,0 +1,3 @@
import { loadEnv } from '#src/env'
loadEnv()

9072
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

74
backend/package.json Normal file
View File

@ -0,0 +1,74 @@
{
"name": "it4c.dev-backend",
"version": "1.0.0",
"description": "IT4C.dev backend",
"license": "Apache-2.0",
"author": "Ulf Gebhardt",
"type": "commonjs",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/IT4Change/IT4C.dev.git"
},
"scripts": {
"start": "node ./build/index.js",
"build": "tsc",
"dev": "tsx watch ./src/index.ts",
"test:unit": "jest",
"test:lint:eslint": "eslint --ext .ts,.tsx,.js,.jsx,.cjs,.mjs,.json,.yml,.yaml --max-warnings 0 .",
"update": "npx npm-check-updates"
},
"devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
"@types/jest": "^29.5.14",
"@types/nodemailer": "^6.4.17",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.24.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-standard": "^17.1.0",
"eslint-import-resolver-typescript": "^3.6.3",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-json": "^3.1.0",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-no-catch-all": "^1.1.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-react": "^7.31.8",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.18",
"eslint-plugin-security": "^3.0.1",
"eslint-plugin-yml": "^1.14.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.6",
"tsx": "^4.19.3",
"typescript": "^5.7.3"
},
"dependencies": {
"@fastify/type-provider-typebox": "^5.1.0",
"fastify": "^5.2.1",
"nodemailer": "^6.10.0",
"ts-dotenv": "^0.9.1"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"setupFiles": [
"./jest/setup.loadEnv.ts"
],
"collectCoverage": true,
"coverageThreshold": {
"global": {
"branches": 100,
"functions": 100,
"lines": 100,
"statements": 100
}
},
"modulePathIgnorePatterns": ["<rootDir>/build/"]
},
"imports": {
"#src/*": "./src/*",
"#root/*": "./*"
}
}

35
backend/src/env.ts Normal file
View File

@ -0,0 +1,35 @@
import { load } from 'ts-dotenv'
import type { EnvType } from 'ts-dotenv'
export const schema = {
NODE_ENV: {
type: ['production' as const, 'development' as const, 'test' as const],
default: 'development',
},
EMAIL_RECEIVER: {
type: String,
default: 'admin@it4c.dev',
},
EMAIL_SUBJECT: {
type: String,
default: '[IT4C] Received EMail from %s',
},
PORT: {
type: Number,
default: 3000,
},
MAIL_HOST: {
type: String,
default: 'localhost',
},
}
export type Env = EnvType<typeof schema>
// eslint-disable-next-line import/no-mutable-exports
export let env: Env
export function loadEnv(): void {
env = load(schema)
}

77
backend/src/formats.ts Normal file
View File

@ -0,0 +1,77 @@
// See: https://github.com/fastify/fastify-type-provider-typebox/issues/84#issuecomment-1560337451
// -------------------------------------------------------------------------------------------
// https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts
// -------------------------------------------------------------------------------------------
/* eslint-disable security/detect-unsafe-regex */
/*
const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i
const DATE_TIME_SEPARATOR = /t|\s/i
const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/
const IPV6 =
/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i
const URL =
/^(?:https?|wss?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu
*/
const EMAIL =
/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i
/*
export function IsLeapYear(year: number): boolean {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)
}
export function IsDate(str: string): boolean {
const matches: string[] | null = DATE.exec(str)
if (!matches) return false
const year: number = +matches[1]
const month: number = +matches[2]
const day: number = +matches[3]
return (
month >= 1 &&
month <= 12 &&
day >= 1 &&
// eslint-disable-next-line security/detect-object-injection
day <= (month === 2 && IsLeapYear(year) ? 29 : DAYS[month])
)
}
export function IsTime(str: string, strictTimeZone?: boolean): boolean {
const matches: string[] | null = TIME.exec(str)
if (!matches) return false
const hr: number = +matches[1]
const min: number = +matches[2]
const sec: number = +matches[3]
const tz: string | undefined = matches[4]
const tzSign: number = matches[5] === '-' ? -1 : 1
const tzH: number = +(matches[6] || 0)
const tzM: number = +(matches[7] || 0)
if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) return false
if (hr <= 23 && min <= 59 && sec < 60) return true
const utcMin = min - tzM * tzSign
const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0)
return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61
}
export function IsDateTime(value: string, strictTimeZone?: boolean): boolean {
const dateTime: string[] = value.split(DATE_TIME_SEPARATOR)
return dateTime.length === 2 && IsDate(dateTime[0]) && IsTime(dateTime[1], strictTimeZone)
}
*/
export function IsEmail(value: string) {
return EMAIL.test(value)
}
/*
export function IsUuid(value: string) {
return UUID.test(value)
}
export function IsUrl(value: string) {
return URL.test(value)
}
export function IsIPv6(value: string) {
return IPV6.test(value)
}
export function IsIPv4(value: string) {
return IPV4.test(value)
}
*/

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

@ -0,0 +1,14 @@
import { loadEnv, env } from './env'
import { createServer } from './server'
loadEnv() // Executed synchronously before the rest of your app loads
const server = createServer(env)
// Run the server!
try {
void server.listen({ port: env.PORT })
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (err) {
server.log.error(err)
process.exit(1)
}

121
backend/src/server.spec.ts Normal file
View File

@ -0,0 +1,121 @@
// eslint-disable-next-line import/no-namespace
import * as nodemailer from 'nodemailer'
import { env } from './env'
import { createServer } from './server'
// Mock nodemailer
jest.mock('nodemailer')
const mockCreateTransport = nodemailer.createTransport as unknown as jest.Mock
const mockSendMail = jest.fn()
mockCreateTransport.mockReturnValue({
sendMail: mockSendMail,
})
const server = createServer(env)
describe('HTTP Server', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('GET / should return 404', async () => {
const response = await server.inject({
method: 'GET',
url: '/',
})
expect(response.statusCode).toBe(404)
})
test('POST /mail without body should return 400 Bad Request', async () => {
const response = await server.inject({
method: 'POST',
url: '/mail',
})
expect(response.statusCode).toBe(400)
expect(JSON.parse(response.body)).toEqual({
success: false,
error: 'Bad Request',
})
})
test('POST /mail with body should return 200 Success', async () => {
const response = await server.inject({
method: 'POST',
url: '/mail',
body: {
name: 'Peter Lustig',
email: 'peter@lustig.de',
text: 'This is my request',
telephone: '+420 55555 55555',
},
})
expect(mockSendMail).toHaveBeenCalledWith({
from: '"Peter Lustig" <peter@lustig.de>',
subject: '[IT4C] Received EMail from Peter Lustig',
text: 'This is my request\n\nTelephone: +420 55555 55555',
to: 'admin@it4c.dev',
})
expect(response.statusCode).toBe(200)
expect(JSON.parse(response.body)).toEqual({
success: true,
})
})
test('POST /mail without telephone should return 200 Success', async () => {
const response = await server.inject({
method: 'POST',
url: '/mail',
body: {
name: 'Peter Lustig',
email: 'peter@lustig.de',
text: 'This is my request',
},
})
expect(mockSendMail).toHaveBeenCalledWith({
from: '"Peter Lustig" <peter@lustig.de>',
subject: '[IT4C] Received EMail from Peter Lustig',
text: 'This is my request',
to: 'admin@it4c.dev',
})
expect(response.statusCode).toBe(200)
expect(JSON.parse(response.body)).toEqual({
success: true,
})
})
test('POST /mail with body and mail delivery failure should return 400', async () => {
mockSendMail.mockImplementationOnce(() => {
throw new Error('Mail Failure')
})
const response = await server.inject({
method: 'POST',
url: '/mail',
body: {
name: 'Peter Lustig',
email: 'peter@lustig.de',
text: 'This is my request',
telephone: '+420 55555 55555',
},
})
expect(mockSendMail).toHaveBeenCalledWith({
from: '"Peter Lustig" <peter@lustig.de>',
subject: '[IT4C] Received EMail from Peter Lustig',
text: 'This is my request\n\nTelephone: +420 55555 55555',
to: 'admin@it4c.dev',
})
expect(response.statusCode).toBe(400)
expect(JSON.parse(response.body)).toEqual({
error: 'Error: Mail Failure',
success: false,
})
})
})

67
backend/src/server.ts Normal file
View File

@ -0,0 +1,67 @@
import util from 'node:util'
import { FormatRegistry, Type, TypeBoxValidatorCompiler } from '@fastify/type-provider-typebox'
import Fastify from 'fastify'
import { createTransport } from 'nodemailer'
import { IsEmail } from './formats'
import type { Env } from './env'
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
function createServer(env: Env) {
// Register EMail format
FormatRegistry.Set('email', (value) => IsEmail(value))
// Nodemailer
const mailService = createTransport({
host: env.MAIL_HOST,
port: 465,
secure: true,
tls: {
rejectUnauthorized: false,
},
})
// Fatify
const fastify = Fastify({
logger: true,
}).setValidatorCompiler(TypeBoxValidatorCompiler)
// Mail
const schema = {
body: Type.Object({
name: Type.String({ minLength: 2, maxLength: 35 }),
email: Type.String({ format: 'email' }),
telephone: Type.Optional(Type.String({ minLength: 8 })),
text: Type.String({ minLength: 5 }),
}),
response: {
200: Type.Object({ success: Type.Boolean({ default: true }) }),
400: Type.Object({
success: Type.Boolean({ default: false }),
error: Type.String(),
}),
},
}
fastify
.withTypeProvider<TypeBoxTypeProvider>()
.post('/mail', { schema }, async (request, reply) => {
try {
await mailService.sendMail({
to: env.EMAIL_RECEIVER,
from: `"${request.body.name}" <${request.body.email}>`,
subject: util.format(env.EMAIL_SUBJECT, request.body.name),
text: `${request.body.text}${request.body.telephone ? `\n\nTelephone: ${request.body.telephone}` : ''}`,
})
return reply.status(200).send({ success: true })
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (error) {
return reply.status(400).send({ success: false, error: error as string })
}
})
return fastify
}
export { createServer }

114
backend/tsconfig.json Normal file
View File

@ -0,0 +1,114 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "NodeNext", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
"paths": { /* Specify a set of entries that re-map imports to additional lookup locations. */
"#src/*": ["./src/*"],
"#root/*": ["./*"]
},
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./build", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}