feat(wip): initial boilerplate

This commit is contained in:
Hasta Ragil Saputra 2021-10-04 16:29:05 +07:00
commit 1b645380e8
23 changed files with 6575 additions and 0 deletions

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
PORT=3222
DATABASE_HOST=
DATABASE_NAME=
DATABASE_USERNAME=
DATABASE_PASSWORD=
DATABASE_PORT=
DATABASE_CLIENT=

196
.eslintrc.js Normal file
View File

@ -0,0 +1,196 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'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',
'no-template-curly-in-string': 'warn',
'array-callback-return': 'warn',
'curly': 'warn',
'dot-location': [
'warn',
'property'
],
'eqeqeq': 'warn',
'no-alert': 'error',
'no-else-return': 'warn',
'no-eval': 'error',
'no-implied-eval': 'error',
'no-labels': 'error',
'no-lone-blocks': 'warn',
'no-param-reassign': [
'warn',
{
'props': true,
'ignorePropertyModificationsFor': [
'ctx',
'target'
]
}
],
'no-return-await': 'warn',
'no-return-assign': 'warn',
'no-self-compare': 'warn',
'no-sequences': 'warn',
'no-throw-literal': 'warn',
'no-unused-expressions': 'warn',
'no-void': 'warn',
'no-useless-concat': 'warn',
'no-console': 'error',
'array-bracket-newline': [
'warn',
'consistent'
],
'array-bracket-spacing': [
'warn',
'never'
],
'block-spacing': 'warn',
'brace-style': 'warn',
'camelcase': 'warn',
'comma-dangle': [
'warn',
'always-multiline'
],
'comma-spacing': 'warn',
'comma-style': 'warn',
'computed-property-spacing': 'warn',
'func-call-spacing': 'warn',
'eol-last': 'warn',
'func-name-matching': 'warn',
'function-call-argument-newline': [
'warn',
'consistent'
],
'indent': [
'warn',
2
],
'linebreak-style': 'warn',
'keyword-spacing': 'warn',
'lines-between-class-members': 'warn',
'no-lonely-if': 'warn',
'no-multi-assign': 'warn',
'no-trailing-spaces': 'warn',
'no-whitespace-before-property': 'warn',
'object-curly-newline': [
'warn',
{
'multiline': true,
'consistent': true
}
],
'object-property-newline': 'warn',
'operator-linebreak': [
'warn',
'after'
],
'padded-blocks': [
'warn',
'never'
],
'padding-line-between-statements': [
'warn',
{
'blankLine': 'always',
'prev': '*',
'next': 'multiline-block-like'
},
{
'blankLine': 'always',
'prev': 'multiline-block-like',
'next': '*'
},
{
'blankLine': 'always',
'prev': '*',
'next': [
'const',
'let',
'export'
]
},
{
'blankLine': 'always',
'prev': [
'const',
'let',
'export'
],
'next': '*'
},
{
'blankLine': 'any',
'prev': [
'const',
'let',
'export'
],
'next': [
'const',
'let',
'export'
]
},
{
'blankLine': 'always',
'prev': '*',
'next': 'return'
}
],
'quotes': [
'warn',
'single',
{ 'allowTemplateLiterals': true }
],
'semi': [
'warn',
'always'
],
'semi-style': 'warn',
'space-before-blocks': 'warn',
'space-in-parens': 'warn',
'space-before-function-paren': [
'warn',
{
'named': 'never',
'anonymous': 'never',
'asyncArrow': 'always'
}
],
'space-infix-ops': 'warn',
'space-unary-ops': 'warn',
'switch-colon-spacing': 'warn',
'arrow-body-style': ['warn', 'always'],
'arrow-parens': [
'warn',
'as-needed',
{
'requireForBlockBody': true
}
],
'no-confusing-arrow': 'warn',
'no-duplicate-imports': 'warn',
'no-var': 'warn',
'prefer-arrow-callback': 'warn',
'prefer-const': 'warn',
'prefer-template': 'warn',
'template-curly-spacing': 'warn'
},
};

37
.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-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
.env

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

73
README.md Normal file
View File

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

4
nest-cli.json Normal file
View File

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

80
package.json Normal file
View File

@ -0,0 +1,80 @@
{
"name": "sppbe-gas-meter",
"version": "0.0.1",
"description": "",
"author": "",
"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": "node dist/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"
},
"dependencies": {
"@nestjs/common": "^8.0.0",
"@nestjs/config": "^1.0.1",
"@nestjs/core": "^8.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/platform-fastify": "^8.0.8",
"@nestjs/typeorm": "^8.0.2",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"joi": "^17.4.2",
"pg": "^8.7.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"typeorm": "^0.2.37",
"typeorm-naming-strategies": "^2.0.0"
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/express": "^4.17.13",
"@types/jest": "^27.0.1",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^4.28.2",
"@typescript-eslint/parser": "^4.28.2",
"eslint": "^7.30.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^27.0.6",
"prettier": "^2.3.2",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

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

@ -0,0 +1,48 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as Joi from 'joi';
import { UsersModule } from './users/users.module';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
import configuration from './config/configuration';
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
validationSchema: Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production', 'test', 'provision')
.default('development'),
PORT: Joi.number().default(3000),
DATABASE_CLIENT: Joi.valid('mysql', 'postgres'),
DATABASE_HOST: Joi.string(),
DATABASE_NAME: Joi.string(),
DATABASE_USERNAME: Joi.string(),
DATABASE_PASSWORD: Joi.string().empty('').default(''),
DATABASE_PORT: Joi.number().default(5432),
}),
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
return {
type: configService.get<'postgres' | 'mysql'>('database.client'),
host: configService.get<string>('database.host'),
port: configService.get<number>('database.port'),
username: configService.get<string>('database.username'),
password: configService.get<string>('database.password'),
database: configService.get<string>('database.name'),
entities: [],
synchronize: true,
autoLoadEntities: true,
logging: true,
namingStrategy: new SnakeNamingStrategy(),
};
},
inject: [ConfigService],
}),
UsersModule,
],
})
export class AppModule {}

View File

@ -0,0 +1,13 @@
export default () => {
return {
port: parseInt(process.env.PORT, 10) || 3000,
database: {
client: process.env.DATABASE_CLIENT,
host: process.env.DATABASE_HOST,
port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD || '',
name: process.env.DATABASE_NAME,
},
};
};

24
src/main.ts Normal file
View File

@ -0,0 +1,24 @@
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);
await app.listen(3000);
}
bootstrap();

View File

@ -0,0 +1,9 @@
import { IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty()
firstName: string;
@IsNotEmpty()
lastName: string;
}

View File

@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';
export class UpdateUserDto extends PartialType(CreateUserDto) {}

View File

@ -0,0 +1,45 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
UpdateDateColumn,
DeleteDateColumn,
VersionColumn,
CreateDateColumn,
} from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
@CreateDateColumn({
type: 'timestamp with time zone',
nullable: false,
})
createdAt: Date;
@UpdateDateColumn({
type: 'timestamp with time zone',
nullable: false,
})
updatedAt: Date;
@DeleteDateColumn({
type: 'timestamp with time zone',
nullable: true,
})
deletedAt: Date;
@VersionColumn()
version: number;
}

View File

@ -0,0 +1,20 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
describe('UsersController', () => {
let controller: UsersController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
}).compile();
controller = module.get<UsersController>(UsersController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,71 @@
import {
Controller,
Get,
Post,
Body,
Put,
Param,
Delete,
ParseUUIDPipe,
HttpStatus,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
async create(@Body() createUserDto: CreateUserDto) {
return {
data: await this.usersService.create(createUserDto),
statusCode: HttpStatus.CREATED,
message: 'success',
};
}
@Get()
async findAll() {
const [data, count] = await this.usersService.findAll();
return {
data,
count,
statusCode: HttpStatus.OK,
message: 'success',
};
}
@Get(':id')
async findOne(@Param('id', ParseUUIDPipe) id: string) {
return {
data: await this.usersService.findOne(id),
statusCode: HttpStatus.OK,
message: 'success',
};
}
@Put(':id')
async update(
@Param('id', ParseUUIDPipe) id: string,
@Body() updateUserDto: UpdateUserDto,
) {
return {
data: await this.usersService.update(id, updateUserDto),
statusCode: HttpStatus.OK,
message: 'success',
};
}
@Delete(':id')
async remove(@Param('id', ParseUUIDPipe) id: string) {
await this.usersService.remove(id);
return {
statusCode: HttpStatus.OK,
message: 'success',
};
}
}

12
src/users/users.module.ts Normal file
View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
import { User } from './entities/user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,84 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { EntityNotFoundError, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
async create(createUserDto: CreateUserDto) {
const result = await this.usersRepository.insert(createUserDto);
return this.usersRepository.findOneOrFail(result.identifiers[0].id);
}
findAll() {
return this.usersRepository.findAndCount();
}
async findOne(id: string) {
try {
return await this.usersRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
}
async update(id: string, updateUserDto: UpdateUserDto) {
try {
await this.usersRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
const result = await this.usersRepository.update(id, updateUserDto);
return this.usersRepository.findOneOrFail(id);
}
async remove(id: string) {
try {
await this.usersRepository.findOneOrFail(id);
} catch (e) {
if (e instanceof EntityNotFoundError) {
throw new HttpException(
{
statusCode: HttpStatus.NOT_FOUND,
error: 'Data not found',
},
HttpStatus.NOT_FOUND,
);
} else {
throw e;
}
}
await this.usersRepository.delete(id);
}
}

24
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

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"]
}

21
tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

5767
yarn.lock Normal file

File diff suppressed because it is too large Load Diff