Skip to content

Commit

Permalink
feature: add new lib server-graphql
Browse files Browse the repository at this point in the history
  • Loading branch information
ldiego73 committed Jun 10, 2020
1 parent b0789c9 commit 09fb90e
Show file tree
Hide file tree
Showing 25 changed files with 280 additions and 107 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
{ "directory": "libs/kernel", "changeProcessCWD": true },
{ "directory": "libs/logger", "changeProcessCWD": true },
{ "directory": "libs/server", "changeProcessCWD": true },
{ "directory": "libs/server-graphql", "changeProcessCWD": true },
{ "directory": "libs/utils", "changeProcessCWD": true },
{ "directory": "microservices/countries/app", "changeProcessCWD": true },
{ "directory": "microservices/countries/config", "changeProcessCWD": true },
Expand Down
12 changes: 12 additions & 0 deletions libs/server-graphql/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false
20 changes: 20 additions & 0 deletions libs/server-graphql/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
parser: "@typescript-eslint/parser"
parserOptions:
project: "tsconfig.json"
sourceType: "module"
plugins:
- "@typescript-eslint/eslint-plugin"
- "simple-import-sort"
extends:
- plugin:@typescript-eslint/eslint-recommended
- plugin:@typescript-eslint/recommended
- prettier
- prettier/@typescript-eslint
env:
node: true
jest: true
rules:
"@typescript-eslint/interface-name-prefix": 0
"@typescript-eslint/explicit-function-return-type": 0
"@typescript-eslint/no-explicit-any": 0
"simple-import-sort/sort": 2
3 changes: 3 additions & 0 deletions libs/server-graphql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
reports/
lib/
16 changes: 16 additions & 0 deletions libs/server-graphql/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Directories
/src
/test

# Others
.babelrc
.editorconfig
.eslintignore
.eslintrc.yml
.gitattributes
.gitignore
.npmignore
.prettierrc
babel.config.js
tsconfig.json
webpack.config.js
7 changes: 7 additions & 0 deletions libs/server-graphql/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"endOfLine": "auto",
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5"
}
9 changes: 9 additions & 0 deletions libs/server-graphql/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2020 Luis Diego

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 changes: 18 additions & 0 deletions libs/server-graphql/jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"transform": {
"^.+\\.ts?$": "ts-jest"
},
"testRegex": ".spec.ts$",
"testEnvironment": "node",
"moduleFileExtensions": [
"ts",
"js"
],
"collectCoverage": true,
"coverageReporters": [
"json",
"text",
"html"
],
"coverageDirectory": "reports"
}
46 changes: 46 additions & 0 deletions libs/server-graphql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "@micro/server-graphql",
"version": "1.0.0",
"description": "Micro Server using NestJS with GraphQL",
"author": {
"name": "Luis Diego",
"email": "[email protected]",
"url": "http://github.com/ldiego73"
},
"license": "MIT",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib/"
],
"scripts": {
"clean": "rimraf reports lib",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\" --loglevel error",
"lint": "eslint \"{src,test}/**/*.ts\" -f stylish",
"prebuild": "yarn clean && yarn format",
"build": "tsc -build tsconfig.build.json",
"test": "jest --passWithNoTests"
},
"dependencies": {
"@micro/server": "^1.0.0",
"@nestjs/graphql": "^7.3.11",
"apollo-server-fastify": "^2.13.1",
"graphql": "^15.0.0",
"graphql-tools": "^6.0.1"
},
"devDependencies": {
"@types/jest": "^25.2.1",
"@types/node": "^14.0.5",
"@typescript-eslint/eslint-plugin": "^3.0.1",
"@typescript-eslint/parser": "^3.0.1",
"eslint": "^7.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.20.2",
"eslint-plugin-simple-import-sort": "^5.0.3",
"jest": "^26.0.1",
"prettier": "^2.0.5",
"rimraf": "^3.0.2",
"ts-jest": "^26.0.0",
"typescript": "^3.8.3"
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApolloError } from "apollo-server-fastify";

import { Exception } from "./exception";
import { Exception } from "@micro/server/lib/exceptions";

export class GraphqlException extends ApolloError {
constructor(props: Exception) {
Expand Down
1 change: 1 addition & 0 deletions libs/server-graphql/src/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./graphql.exception";
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BaseExceptionFilter, Response } from "@micro/server/lib/filters";
import { ArgumentsHost, Catch } from "@nestjs/common";
import {
GqlArgumentsHost,
Expand All @@ -7,7 +8,6 @@ import {
import { GraphQLResolveInfo } from "graphql";

import { GraphqlException } from "../exceptions";
import { BaseExceptionFilter, Response } from "./base.exception.filter";

@Catch()
export class GraphQlExceptionFilter extends BaseExceptionFilter
Expand Down
1 change: 1 addition & 0 deletions libs/server-graphql/src/filters/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./graphql-exception.filter";
1 change: 1 addition & 0 deletions libs/server-graphql/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./server";
17 changes: 17 additions & 0 deletions libs/server-graphql/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { BaseServer, ServerOptions } from "@micro/server/lib/core";
import { HttpExceptionFilter } from "@micro/server/lib/filters";

import { GraphQlExceptionFilter } from "./filters";

export class Server extends BaseServer {
protected async bootstrap(appModule: unknown): Promise<void> {
await this.defaultBootstrap(appModule);

this.app.useGlobalFilters(new HttpExceptionFilter());
this.app.useGlobalFilters(new GraphQlExceptionFilter());
}

public static create(appModule: unknown, options: ServerOptions): Server {
return new Server(appModule, options);
}
}
Empty file.
4 changes: 4 additions & 0 deletions libs/server-graphql/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "dist", "test"]
}
18 changes: 18 additions & 0 deletions libs/server-graphql/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2019",
"module": "CommonJS",
"lib": ["ES2019"],
"declaration": true,
"strict": true,
"esModuleInterop": true,
"noImplicitAny": true,
"resolveJsonModule": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"outDir": "lib"
},
"include": ["src/**/*", "test/**/*"],
"exclude": ["node_modules", "lib"]
}
6 changes: 1 addition & 5 deletions libs/server/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@micro/server",
"version": "1.0.0",
"description": "A simple logging library that encapsulates console.log",
"description": "Micro Server using NestJS",
"author": {
"name": "Luis Diego",
"email": "[email protected]",
Expand All @@ -26,13 +26,9 @@
"@micro/utils": "^1.0.0",
"@nestjs/common": "^7.1.0",
"@nestjs/core": "^7.1.0",
"@nestjs/graphql": "^7.3.11",
"@nestjs/platform-fastify": "^7.1.0",
"apollo-server-fastify": "^2.13.1",
"fastify-compress": "^2.0.1",
"fastify-helmet": "^3.0.2",
"graphql": "^15.0.0",
"graphql-tools": "^6.0.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^6.5.5"
},
Expand Down
97 changes: 97 additions & 0 deletions libs/server/src/core/base.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { Logger } from "@micro/logger";
import { NestFactory } from "@nestjs/core";
import {
FastifyAdapter,
NestFastifyApplication,
} from "@nestjs/platform-fastify";
import { ServerOptionsAsSecureHttp } from "fastify";
import compression from "fastify-compress";
import helmet from "fastify-helmet";
import fs from "fs";
import path from "path";

import { ServerOptions } from "./options";

const readCert = (cert: string): Buffer =>
fs.readFileSync(path.join(process.cwd(), cert));

export abstract class BaseServer {
protected log: Logger;
protected app!: NestFastifyApplication;
protected plugins: any[] = [];
protected readonly appModule: unknown;
protected readonly options: ServerOptions;

protected constructor(appModule: unknown, options: ServerOptions) {
if (appModule === null || appModule === undefined) {
throw new Error("Unable to retrieve app module");
}

this.log = Logger.create(this.constructor.name);
this.appModule = appModule;
this.options = Object.assign(
{
port: 3000,
logger: true,
stack: true,
} as ServerOptions,
options
);
}

protected createHttpsOptions(): ServerOptionsAsSecureHttp {
if (this.options.https) {
return {
https: {
allowHTTP1: true,
key: readCert(this.options.https.key),
cert: readCert(this.options.https.cert),
},
};
} else {
throw new Error("Unable to retrieve https values");
}
}

protected adapter(): FastifyAdapter {
let adapter: FastifyAdapter;

if (!this.options.https) {
adapter = new FastifyAdapter();
} else {
adapter = new FastifyAdapter(this.createHttpsOptions());
}

return adapter;
}

public register(...args: any[]): void {
this.plugins.push(args);
}

protected async defaultBootstrap(appModule: unknown): Promise<void> {
this.app = await NestFactory.create<NestFastifyApplication>(
appModule,
this.adapter(),
{
logger: this.options.logger ? ["error", "warn"] : false,
}
);

this.app.register(helmet);
this.app.register(compression, { encodings: ["gzip", "deflate"] });

this.plugins.forEach((p) => {
this.app.register(...p);
});
}

protected abstract bootstrap(appModule: unknown): Promise<void>;

public async start(): Promise<void> {
await this.bootstrap(this.appModule);
await this.app.listen(this.options.port);

this.log.info(`Server listening at ${await this.app.getUrl()}`);
}
}
1 change: 1 addition & 0 deletions libs/server/src/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./base.controller";
export * from "./base.server";
export * from "./base.service";
export * from "./base.resolver";
export * from "./options";
1 change: 0 additions & 1 deletion libs/server/src/core/options.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export interface ServerOptions {
port: number;
logger?: boolean;
graphql?: boolean;
stack?: boolean;
https?: ServerHttpsOptions;
}
Expand Down
1 change: 0 additions & 1 deletion libs/server/src/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from "./exception";
export * from "./http.exception";
export * from "./graphql.exception";
1 change: 0 additions & 1 deletion libs/server/src/filters/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export * from "./base.exception.filter";
export * from "./graphql-exception.filter";
export * from "./http-exception.filter";
Loading

0 comments on commit 09fb90e

Please sign in to comment.