├── .env ├── .env.development ├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .npmrc ├── README.md ├── package.json ├── public └── index.html ├── src ├── index.ts └── lib │ ├── config.ts │ ├── createServer.ts │ └── routes │ └── ping │ ├── ping.test.ts │ └── ping.ts └── tsconfig ├── tsconfig.base.json ├── tsconfig.dev.json ├── tsconfig.eslint.json └── tsconfig.prod.json /.env: -------------------------------------------------------------------------------- 1 | API_HOST=0.0.0.0 2 | API_PORT=5000 3 | NODE_ENV=production -------------------------------------------------------------------------------- /.env.development: -------------------------------------------------------------------------------- 1 | API_HOST=0.0.0.0 2 | API_PORT=5000 3 | NODE_ENV=development -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | coverage -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "project": ["./tsconfig/tsconfig.eslint.json"] 6 | }, 7 | "plugins": [ 8 | "@typescript-eslint" 9 | ], 10 | "extends": [ 11 | "eslint:recommended", 12 | "plugin:@typescript-eslint/recommended", 13 | "plugin:@typescript-eslint/recommended-requiring-type-checking" 14 | ], 15 | "rules": { 16 | "@typescript-eslint/explicit-module-boundary-types": "off", 17 | "@typescript-eslint/require-await": "off", 18 | "@typescript-eslint/no-floating-promises": ["error", { "ignoreVoid": true }] 19 | } 20 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | .nyc_output 4 | 5 | # In a real project don't commit your env variables; we only ship them here for sample purposes 6 | # .env -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastify-typescript-extended-sample 2 | 3 | ⚠ Work In Progress 4 | 5 | This project is supposed to be a large, fake Fastify & TypeScript app. It is meant to be a reference as well as a pseudo-sandbox for Fastify TypeScript changes. 6 | 7 | Contributions are always welcome! 8 | 9 | > Disclaimer: 10 | > This repo is not the **only** way to build a Fastify App. It is just _one_ way to do so that plays nicely with TypeScript. 11 | 12 | Based heavily off of [covid-green-backend-api](https://github.com/covidgreen/covid-green-backend-api) Nearform project. 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fastify-typescript-extended-sample", 3 | "version": "1.0.0", 4 | "description": "This project is supposed to be a large, fake Fastify & TypeScript app. It is meant to be a reference as well as a pseudo-sandbox for Fastify TypeScript changes.", 5 | "main": "build/index.js", 6 | "scripts": { 7 | "dev": "ts-node-dev -P tsconfig/tsconfig.dev.json -r dotenv/config src/index.ts dotenv_config_path=.env.development", 8 | "build": "tsc -p tsconfig/tsconfig.prod.json", 9 | "start": "node -r dotenv/config build/index.js dotenv_config_path=.env", 10 | "lint": "eslint .", 11 | "test": "tap **/*.test.ts" 12 | }, 13 | "keywords": [], 14 | "author": "Ethan Arrowood", 15 | "license": "MIT", 16 | "devDependencies": { 17 | "@types/node": "^14.10.1", 18 | "@types/tap": "^14.10.1", 19 | "@typescript-eslint/eslint-plugin": "^4.1.1", 20 | "@typescript-eslint/parser": "^4.1.1", 21 | "eslint": "^7.9.0", 22 | "tap": "^14.10.8", 23 | "typescript": "^4.0.2" 24 | }, 25 | "dependencies": { 26 | "@sinclair/typebox": "^0.10.1", 27 | "dotenv": "^8.2.0", 28 | "env-var": "^6.3.0", 29 | "fastify": "^3.4.1", 30 | "fastify-autoload": "^3.3.0", 31 | "fastify-static": "^3.2.1", 32 | "fluent-schema": "^1.0.4", 33 | "ts-node": "^9.0.0", 34 | "ts-node-dev": "^1.0.0-pre.62" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Fastify Web App FrontEnd 7 | 8 | 9 |

👻

10 | 11 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { FastifyInstance } from 'fastify' 2 | import { getConfig } from './lib/config' 3 | import createServer from './lib/createServer' 4 | 5 | async function run () { 6 | process.on('unhandledRejection', err => { 7 | console.error(err) 8 | process.exit(1) 9 | }) 10 | 11 | const config = getConfig() 12 | 13 | // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-var-requires 14 | const app = require('fastify')(config.fastifyInit) as FastifyInstance 15 | void app.register(createServer, { config }) 16 | 17 | await app.listen(config.fastify) 18 | } 19 | 20 | void run() -------------------------------------------------------------------------------- /src/lib/config.ts: -------------------------------------------------------------------------------- 1 | import envVar from 'env-var' 2 | 3 | export function getConfig () { 4 | const env = { 5 | NODE_ENV: envVar.get('NODE_ENV').required().asString(), 6 | API_HOST: envVar.get('API_HOST').required().asString(), 7 | API_PORT: envVar.get('API_PORT').required().asPortNumber() 8 | } 9 | 10 | const isProduction = /^\s*production\s*$/i.test(env.NODE_ENV) 11 | 12 | return { 13 | isProduction, 14 | fastify: { 15 | host: env.API_HOST, 16 | port: env.API_PORT 17 | }, 18 | fastifyInit: { 19 | logger: true 20 | } 21 | } 22 | } 23 | 24 | export function getTestingConfig(): Config { 25 | return { 26 | isProduction: false, 27 | fastify: { 28 | host: '0.0.0.0', 29 | port: 5000 30 | }, 31 | fastifyInit: { 32 | logger: false 33 | } 34 | } 35 | } 36 | 37 | export type Config = ReturnType -------------------------------------------------------------------------------- /src/lib/createServer.ts: -------------------------------------------------------------------------------- 1 | import { FastifyPluginAsync } from 'fastify' 2 | import autoload from 'fastify-autoload' 3 | import path from 'path' 4 | import { Config } from './config' 5 | import fastifyStatic from 'fastify-static' 6 | 7 | export interface PluginOpts { 8 | config: Config 9 | } 10 | 11 | export type Plugin = FastifyPluginAsync 12 | 13 | const createServer: Plugin = async (server, opts) => { 14 | void server.register(fastifyStatic, { 15 | root: path.join(process.cwd(), '/public'), 16 | prefixAvoidTrailingSlash: true 17 | }) 18 | 19 | server.setNotFoundHandler((_, reply) => { 20 | void reply.sendFile('404.html') 21 | }) 22 | 23 | void server.register(autoload, { 24 | dir: path.join(__dirname, 'routes'), 25 | ignorePattern: /.test.(t|j)s/, 26 | dirNameRoutePrefix: false, 27 | options: { 28 | prefix: '/api', 29 | config: opts.config 30 | } 31 | }) 32 | } 33 | 34 | export default createServer -------------------------------------------------------------------------------- /src/lib/routes/ping/ping.test.ts: -------------------------------------------------------------------------------- 1 | import t from 'tap' 2 | import { FastifyInstance } from 'fastify' 3 | 4 | import ping from './ping' 5 | import { getTestingConfig } from '../../config' 6 | 7 | void t.test('ping should return pong', async t => { 8 | t.plan(2) 9 | 10 | const config = getTestingConfig() 11 | // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-var-requires 12 | const server = require('fastify')(config.fastifyInit) as FastifyInstance 13 | await server.register(ping, { config }).ready() 14 | 15 | const res = await server.inject({ 16 | method: 'GET', 17 | url: '/ping' 18 | }) 19 | 20 | t.equal(res.statusCode, 200) 21 | t.equal(res.payload, 'pong\n') 22 | 23 | await server.close() 24 | }) -------------------------------------------------------------------------------- /src/lib/routes/ping/ping.ts: -------------------------------------------------------------------------------- 1 | import { Plugin } from '../../createServer' 2 | 3 | const ping: Plugin = async server => { 4 | server.route({ 5 | url: '/ping', 6 | method: 'GET', 7 | handler: async () => { 8 | return 'pong\n' 9 | } 10 | }) 11 | } 12 | 13 | export default ping -------------------------------------------------------------------------------- /tsconfig/tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | "incremental": true, /* Enable incremental compilation */ 7 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./../build", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 67 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 68 | } 69 | } -------------------------------------------------------------------------------- /tsconfig/tsconfig.dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "compilerOptions": { 4 | "sourceMap": true, 5 | }, 6 | "include": [ 7 | "../src/**/*.ts" 8 | ], 9 | "exclude": [ 10 | "../src/**/*.test.ts" 11 | ] 12 | } -------------------------------------------------------------------------------- /tsconfig/tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "include": [ 4 | "../src/**/*.ts", 5 | ] 6 | } -------------------------------------------------------------------------------- /tsconfig/tsconfig.prod.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "include": [ 4 | "../src/**/*.ts" 5 | ], 6 | "exclude": [ 7 | "../src/**/*.test.ts" 8 | ] 9 | } --------------------------------------------------------------------------------