Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ilijaNL committed Mar 30, 2023
0 parents commit 2bc4d26
Show file tree
Hide file tree
Showing 54 changed files with 3,873 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
**/node_modules/
**/npm-debug.log
**/.env
**/dist
**/bin
.git
**/out
**/.next
**/tsconfig.tsbuildinfo
db/
docker/**
**/.turbo
36 changes: 36 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# These are some examples of commonly ignored file patterns.
# You should customize this list as applicable to your project.
# Learn more about .gitignore:
# https://www.atlassian.com/git/tutorials/saving-changes/gitignore

# Node artifact files
**/node_modules/
**/dist/
**/build/

# sql dumps
db/dumps/

.docker
.env
*.tar
.DS_Store
.turbo
*.tsbuildinfo

.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions

# Swap the comments on the following lines if you don't wish to use zero-installs
# Documentation here: https://yarnpkg.com/features/zero-installs
#!.yarn/cache
.pnp.*


cypress.env.json

out/
5 changes: 5 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
*.yaml
*.yml
*.env
*.generated.*
8 changes: 8 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"bracketSpacing": true,
"printWidth": 120,
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 2,
"useTabs": false
}
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# TS Hasura Fastify Starter

A starter template for hasura, fastify, nextjs and postgres
10 changes: 10 additions & 0 deletions apps/api/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
**/node_modules/**
npm-debug.log
.env
dist
bin
.nyc_output
coverage/
tests/
turbo/
vscode/
10 changes: 10 additions & 0 deletions apps/api/bootstrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const tsConfig = require('./tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');
const path = require('node:path');

const baseUrl = path.join(__dirname, 'dist');

tsConfigPaths.register({
baseUrl,
paths: tsConfig.compilerOptions.paths
});
4 changes: 4 additions & 0 deletions apps/api/example.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
NODE_ENV=development
PORT=3001
PG_CONNECTION=postgres://postgres:postgres@localhost:5432/app

58 changes: 58 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"name": "api",
"author": "IlijaNL",
"private": true,
"version": "0.0.1",
"scripts": {
"tc": "tsc --noEmit",
"dev": "tsx watch --clear-screen=false src/server.ts",
"format": "prettier --write src",
"build": "rimraf dist && tsc",
"start": "node -r ./bootstrap.js dist/server.js",
"test": "tap --node-arg=--require=tsconfig-paths/register --ts --no-cov"
},
"license": "MIT",
"dependencies": {
"@fastify/auth": "^4.2.0",
"@fastify/cookie": "^8.3.0",
"@fastify/cors": "^8.2.1",
"@fastify/helmet": "^10.1.0",
"@fastify/rate-limit": "^8.0.0",
"@fastify/sensible": "^5.2.0",
"@fastify/type-provider-typebox": "^3.0.0",
"@sinclair/typebox": "^0.26.6",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"date-fns": "^2.25.0",
"delay": "^5.0.0",
"dotenv": "^16.0.3",
"fast-jwt": "^2.2.0",
"fastify": "^4.15.0",
"fastify-plugin": "^4.5.0",
"http-errors": "^2.0.0",
"lodash": "^4.17.21",
"node-batcher": "^0.1.1",
"nodemailer": "^6.9.1",
"pg": "^8.10.0",
"pg-tbus": "^0.1.1",
"safe-stable-stringify": "^2.4.3",
"ts-pattern": "^4.2.2",
"tsconfig-paths": "^4.2.0",
"undici": "^5.21.0"
},
"devDependencies": {
"@types/http-errors": "^2.0.1",
"@types/lodash": "^4.14.176",
"@types/node": "^16.0.0",
"@types/pg": "^8.6.4",
"@types/tap": "^15.0.8",
"close-with-grace": "^1.1.0",
"prettier": "^2.4.1",
"rimraf": "^4.4.1",
"tap": "^16.3.4",
"ts-node": "^10.7.0",
"tsconfig": "workspace:*",
"tsx": "^3.12.6",
"typescript": "^4.9.0"
}
}
1 change: 1 addition & 0 deletions apps/api/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fastify API
37 changes: 37 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { FastifyPluginAsync, FastifyServerOptions, RouteOptions } from 'fastify';
import fp from 'fastify-plugin';
import fastifyHelmet from '@fastify/helmet';
import _ from 'lodash';
import sensible from '@fastify/sensible';
import environment from './env';

const IS_PROD = environment.NODE_ENV === 'production';

const app: FastifyPluginAsync = async (fastify) => {
if (IS_PROD) {
await fastify.register(fastifyHelmet);
}

if (!IS_PROD) {
await fastify.register(
fp(async function (instance) {
instance.addHook('onRoute', (route: RouteOptions) => {
instance.log.info(`${route.url}`);
});
})
);
}

await fastify.register(sensible);

fastify.get('/_health', (_, reply) => {
return reply.status(200).send('ok');
});
};

// this will be used by fastify cli
export const options: FastifyServerOptions = {
trustProxy: true,
};

export default app;
14 changes: 14 additions & 0 deletions apps/api/src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require('dotenv').config();

import { Type } from '@sinclair/typebox';
import { parseEnvs } from 'utils/env';

const ENVS = parseEnvs(
Type.Object({
PORT: Type.String(),
PG_CONNECTION: Type.String(),
NODE_ENV: Type.Union((['production', 'staging', 'development'] as const).map((c) => Type.Literal(c))),
})
);

export default ENVS;
47 changes: 47 additions & 0 deletions apps/api/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import fastify from 'fastify';
import closeWithGrace from 'close-with-grace';
import environment from './env';
import app, { options } from './app';

const IS_PROD = environment.NODE_ENV === 'production';

// Instantiate Fastify with some config
const server = fastify({
logger: {
level: IS_PROD ? 'error' : 'info',
},
...options,
});

server.register(app);

const closeListeners = closeWithGrace({ delay: 5000 }, async ({ err }: any) => {
if (err) {
server.log.error(err);
}

server.log.info('closing api');

await server.close();
});

server.addHook('onClose', async (_, done) => {
closeListeners.uninstall();

done();
});

// Start listening.
// use 0.0.0.0 for docker
server.listen(
{
// host: '0.0.0.0',
port: +environment.PORT,
},
(err) => {
if (err) {
server.log.error(err);
process.exit(1);
}
}
);
24 changes: 24 additions & 0 deletions apps/api/src/utils/encryption.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import crypto from 'crypto';

const ENCRYPTION_KEY: string = process.env.SC_ENCRYPTION_KEY || ''; // Must be 256 bits (32 characters)
const IV_LENGTH: number = 16; // For AES, this is always 16

export function encrypt(text: string, encryptionKey: string = ENCRYPTION_KEY): string {
let iv = Buffer.from(crypto.randomBytes(IV_LENGTH)).toString('hex').slice(0, IV_LENGTH);
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(encryptionKey), iv);
let encrypted = cipher.update(text);

encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv + ':' + encrypted.toString('hex');
}

export function decrypt(text: string, encryptionKey: string = ENCRYPTION_KEY): string {
let textParts: string[] = text.includes(':') ? text.split(':') : [];
let iv = Buffer.from(textParts.shift() || '', 'binary');
let encryptedText = Buffer.from(textParts.join(':'), 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(encryptionKey), iv);
let decrypted = decipher.update(encryptedText);

decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
14 changes: 14 additions & 0 deletions apps/api/src/utils/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Static, TSchema } from '@sinclair/typebox';
import { createValidateFn } from './schema';

export function parseEnvs<T extends TSchema>(schema: T) {
const fn = createValidateFn(schema);
const environment = process.env;

if (!fn(environment)) {
console.log({ errors: fn.errors });
throw new Error('missing envs: ' + fn.errors?.map((e) => e.message).join(', '));
}

return environment as Static<T>;
}
Loading

0 comments on commit 2bc4d26

Please sign in to comment.