initial commit

master
Lauren Liberda 2021-07-08 19:40:14 +02:00
commit 226cabfc05
24 changed files with 8796 additions and 0 deletions

5
.env.sample Normal file
View File

@ -0,0 +1,5 @@
NODE_ENV='development'
PG_HOST='127.0.0.1'
PG_DATABASE='metropolis'
PG_USERNAME='metro'
PG_PASSWORD='polis'

24
.eslintrc.js Normal file
View File

@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'airbnb-typescript/base',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

36
.gitignore vendored Normal file
View File

@ -0,0 +1,36 @@
.env
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"editor.tabSize": 2
}

27
Dockerfile Normal file
View File

@ -0,0 +1,27 @@
FROM node:16-alpine AS build
WORKDIR /app
COPY package.json .
COPY yarn.lock .
RUN yarn install --frozen-lockfile
COPY tsconfig.json .
COPY tsconfig.build.json .
COPY migration .
COPY src .
RUN yarn build
FROM node:16-alpine AS prod
WORKDIR /app
ENV NODE_ENV production
COPY package.json .
COPY yarn.lock .
RUN yarn install --production --frozen-lockfile
COPY --from=build /app/dist dist
CMD ["yarn", "start:prod"]

46
README.md Normal file
View File

@ -0,0 +1,46 @@
# Metropolis
## Installation
```bash
$ yarn
# edit this file to match your environment
$ cp .env.sample .env
```
## Running the app
```bash
# postgres - required by the app
$ docker-compose up -d postgres
# migrations - required to apply before the app runs first time,
# and after new migrations appear
$ yarn migration:run
# development
$ yarn start
# watch mode
$ yarn start:dev
# production mode
$ yarn start:prod
```
## Test
No automatic tests, use cURL or Insomnia.
<!--
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
-->

23
docker-compose.yml Normal file
View File

@ -0,0 +1,23 @@
version: '3.1'
services:
metropolis:
depends_on:
- postgres
build:
dockerfile: Dockerfile
context: .
environment:
PG_HOST: postgres
PG_DATABASE: metropolis
PG_USERNAME: metro
PG_PASSWORD: polis
postgres:
image: postgres:13-alpine
environment:
POSTGRES_DB: metropolis
POSTGRES_USER: metro
POSTGRES_PASSWORD: polis
ports:
- 127.0.0.1:5432:5432

View File

@ -0,0 +1,42 @@
import { MigrationInterface, QueryRunner, Table, TableColumn } from 'typeorm';
export class initialize1625694002469 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE SEQUENCE items_serial
AS bigint
MINVALUE 140000000000
START WITH 140000000000;
`);
const items = new Table();
items.name = 'item';
const iid = new TableColumn();
iid.name = 'id';
iid.type = 'bigint';
iid.default = "nextval('items_serial')";
iid.isPrimary = true;
iid.isUnique = true;
iid.isNullable = false;
items.addColumn(iid);
const iname = new TableColumn();
iname.name = 'name';
iname.type = 'varchar(40)';
iname.isNullable = false;
items.addColumn(iname);
const inotes = new TableColumn();
inotes.name = 'notes';
inotes.type = 'varchar(255)';
inotes.isNullable = true;
items.addColumn(inotes);
await queryRunner.createTable(items);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('items');
await queryRunner.query(`
DROP SEQUENCE items_serial;
`);
}
}

4
nest-cli.json Normal file
View File

@ -0,0 +1,4 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

15
ormconfig.js Normal file
View File

@ -0,0 +1,15 @@
const { PG_HOST, PG_PORT, PG_USERNAME, PG_PASSWORD, PG_DATABASE } = process.env;
module.exports = {
type: 'postgres',
host: PG_HOST || '127.0.0.1',
port: parseInt(PG_PORT || '5432', 10),
username: PG_USERNAME,
password: PG_PASSWORD,
database: PG_DATABASE,
entities: [],
migrations: ['dist/migration/*.js'],
cli: {
migrationsDir: 'migration',
},
};

77
package.json Normal file
View File

@ -0,0 +1,77 @@
{
"name": "metropolis",
"version": "0.0.1",
"author": "Lauren Liberda <laura@selfisekai.rocks>",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "yarn migration:run && node dist/src/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"migration:run": "typeorm migration:run"
},
"dependencies": {
"@nestjs/common": "^7.6.15",
"@nestjs/config": "^1.0.0",
"@nestjs/core": "^7.6.15",
"@nestjs/graphql": "^7.11.0",
"@nestjs/platform-fastify": "^7.6.18",
"@nestjs/typeorm": "^7.1.5",
"apollo-server-fastify": "^2.25.2",
"dotenv": "^10.0.0",
"graphql": "^15.5.1",
"graphql-tools": "^7.0.5",
"pg": "^8.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.6",
"typeorm": "^0.2.34"
},
"devDependencies": {
"@nestjs/cli": "^7.6.0",
"@nestjs/schematics": "^7.3.0",
"@nestjs/testing": "^7.6.15",
"@types/dotenv": "^8.2.0",
"@types/jest": "^26.0.22",
"@types/node": "^14.14.36",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"eslint": "^7.22.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"ts-jest": "^26.5.4",
"ts-loader": "^8.0.18",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

31
src/app.module.ts Normal file
View File

@ -0,0 +1,31 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLModule } from '@nestjs/graphql';
import { ConfigModule } from '@nestjs/config';
import { getConnectionOptions } from 'typeorm';
import path from 'path';
import { ItemsModule } from './items/items.module';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env',
}),
ItemsModule,
TypeOrmModule.forRootAsync({
useFactory: async () => ({
...(await getConnectionOptions()),
autoLoadEntities: true,
}),
}),
GraphQLModule.forRoot({
// debug: false,
playground: false,
path: '/api/graphql',
autoSchemaFile: path.join(__dirname, 'schema.gql'),
}),
],
controllers: [],
providers: [],
})
export class AppModule {}

View File

@ -0,0 +1,10 @@
import { Field, ID, InputType } from '@nestjs/graphql';
@InputType()
export class NewItemInput {
@Field()
name: string;
@Field({ nullable: true })
notes?: string;
}

13
src/items/items.entity.ts Normal file
View File

@ -0,0 +1,13 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Item {
@PrimaryGeneratedColumn('increment')
id: number;
@Column()
name: string;
@Column({ nullable: true })
notes?: string;
}

15
src/items/items.model.ts Normal file
View File

@ -0,0 +1,15 @@
import { Field, ID, ObjectType } from '@nestjs/graphql';
@ObjectType('Item', {
description: 'Either the inventored thing or a box containing them',
})
export class ItemModel {
@Field((type) => ID)
id: string;
@Field()
name: string;
@Field({ nullable: true })
notes?: string;
}

14
src/items/items.module.ts Normal file
View File

@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { ItemsResolver } from './items.resolver';
import { ItemsService } from './items.service';
import { Item } from './items.entity';
@Module({
imports: [TypeOrmModule.forFeature([Item])],
providers: [ItemsResolver, ItemsService],
})
export class ItemsModule {
constructor(private connection: Connection) {}
}

View File

@ -0,0 +1,19 @@
import { Args, ID, Mutation, Query, Resolver } from '@nestjs/graphql';
import { NewItemInput } from './dto/new-item.input';
import { ItemModel } from './items.model';
import { ItemsService } from './items.service';
@Resolver((of) => ItemModel)
export class ItemsResolver {
constructor(private itemsService: ItemsService) {}
@Query((returns) => ItemModel, { nullable: true })
async item(@Args('id', { type: () => ID }) id: string) {
return this.itemsService.getItem(id);
}
@Mutation((returns) => ItemModel)
async createItem(@Args('itemData') itemData: NewItemInput) {
return this.itemsService.createItem(itemData);
}
}

View File

@ -0,0 +1,24 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NewItemInput } from './dto/new-item.input';
import { Item } from './items.entity';
@Injectable()
export class ItemsService {
constructor(
@InjectRepository(Item)
private itemRepository: Repository<Item>,
) {}
async getItem(id: string): Promise<Item | undefined> {
return this.itemRepository.findOne(id);
}
async createItem(input: NewItemInput): Promise<Item> {
const item = new Item();
item.name = input.name;
item.notes = input.notes;
return this.itemRepository.save(item);
}
}

17
src/main.ts Normal file
View File

@ -0,0 +1,17 @@
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
const { PORT } = process.env;
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
await app.listen(PORT ? parseInt(PORT, 10) : 3333, '0.0.0.0');
}
bootstrap();

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

72
tsconfig.json Normal file
View File

@ -0,0 +1,72 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
"incremental": true /* Enable incremental compilation */,
"target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"removeComments": true /* Do not emit comments to output. */,
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": false /* Enable all strict type-checking options. */,
// "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

8261
yarn.lock Normal file

File diff suppressed because it is too large Load Diff