├── lib ├── provider.map.ts ├── interfaces │ ├── index.ts │ ├── filter.ts │ └── options.ts ├── index.ts ├── mailmanConfig.ts ├── resources │ └── template.ts ├── facade.ts ├── http.ts ├── module.ts └── service.ts ├── .gitignore ├── tsconfig.json ├── LICENSE.md ├── README.md ├── package.json └── CONTRIBUTING.md /lib/provider.map.ts: -------------------------------------------------------------------------------- 1 | export const EYEWITNESS_OPTIONS = 'EYEWITNESS_OPTIONS'; 2 | -------------------------------------------------------------------------------- /lib/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./options"; 2 | export * from "./filter"; 3 | -------------------------------------------------------------------------------- /lib/interfaces/filter.ts: -------------------------------------------------------------------------------- 1 | export interface EyewitnessContract { 2 | report(): Array; 3 | } 4 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./module"; 2 | export * from "./service"; 3 | export * from "./facade"; 4 | export * from "./interfaces"; 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | /node_modules 3 | 4 | # IDE 5 | /.idea 6 | /.awcache 7 | /.vscode 8 | 9 | # misc 10 | npm-debug.log 11 | .DS_Store 12 | 13 | # tests 14 | /test 15 | /coverage 16 | /.nyc_output 17 | 18 | # dist 19 | dist -------------------------------------------------------------------------------- /lib/mailmanConfig.ts: -------------------------------------------------------------------------------- 1 | import { 2 | MailmanOptions, 3 | MailmanOptionsFactory, 4 | } from '@squareboat/nest-mailman'; 5 | import { EyewitnessService } from './service'; 6 | import { EyewitnessModule } from './module'; 7 | 8 | export class MailmanConfigFactory implements MailmanOptionsFactory { 9 | createMailmanOptions(): MailmanOptions | Promise { 10 | return EyewitnessService.getConfig().mailman; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "strict": true, 6 | "removeComments": true, 7 | "noLib": false, 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es6", 11 | "sourceMap": false, 12 | "outDir": "./dist", 13 | "rootDir": "./lib", 14 | "skipLibCheck": true 15 | }, 16 | "include": ["lib/**/*"], 17 | "exclude": ["node_modules", "**/*.spec.ts", "tests"] 18 | } 19 | -------------------------------------------------------------------------------- /lib/resources/template.ts: -------------------------------------------------------------------------------- 1 | export const TEMPLATE = ` 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
Message:{{ exception.message }}
REQUEST URL:{{ request.url }}
REQUEST PAYLOAD:{{ request.payload }}
REQUEST HEADERS:{{ request.headers }}
STACK:{{ exception.stack }}
REQUEST TIMESTAMP{{ request.timestamp }}
`; 38 | -------------------------------------------------------------------------------- /lib/facade.ts: -------------------------------------------------------------------------------- 1 | import { ArgumentsHost } from "@nestjs/common"; 2 | import { EyewitnessService } from "./service"; 3 | 4 | export class Eyewitness { 5 | private static doNotReportExceptions: any[] = []; 6 | 7 | /** 8 | * Function for adding exceptions to "doNoReport" list. 9 | * @param exceptions 10 | */ 11 | static doNotReport(exceptions: Array) { 12 | const exceptionNames: any[] = []; 13 | exceptions.forEach((e) => { 14 | exceptionNames.push(e.name); 15 | }); 16 | Eyewitness.doNotReportExceptions = exceptionNames; 17 | } 18 | 19 | /** 20 | * Watch the exception filter, runs on every thrown exception 21 | * @param exception 22 | * @param host 23 | */ 24 | static watch(exception: any, host: ArgumentsHost) { 25 | if (Eyewitness.doNotReportExceptions.includes(exception.constructor.name)) { 26 | return; 27 | } 28 | 29 | const ctx = host.switchToHttp(); 30 | const request = ctx.getRequest(); 31 | 32 | EyewitnessService.alert(exception, host); 33 | 34 | return {}; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright © 2020 [SquareBoat](https://squareboat.com) 4 | 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in 13 | > all copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | > THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Nest Eyewitness 2 | 3 | A simple easy-to-use package to receive error reports directly to your inbox whenever any exception is witnessed 👀 in your NestJS application. 4 | 5 | Be the first one to know about the error as soon as it happens and take action. 6 | 7 | ### Features 8 | 9 | - ✅ Email first error reporter 10 | - ✅ Comprehensive support for custom webhooks 11 | - ✅ Access to complete stack trace for easy debugging and decision making 12 | - ✅ Fast Integration and comprehensive documentation 13 | 14 | For complete documentation, head over to [our site](https://opensource.squareboat.com/nest-eyewitness). 15 | 16 | --- 17 | 18 | ## Contributing 19 | 20 | Please see our contributing [guidelines](./CONTRIBUTING.md). 21 | 22 | ## About Us 23 | 24 | We are a bunch of dreamers, designers, and futurists. We are high on collaboration, low on ego, and take our happy hours seriously. We'd love to hear more about your product. Let's talk and turn your great ideas into something even greater! We have something in store for everyone. [☎️ 📧 Connect with us!](https://squareboat.com/contact) 25 | 26 | ---- 27 | 28 | ## License 29 | 30 | The MIT License. Please see License File for more information. Copyright © 2020 SquareBoat. 31 | 32 | Made with ❤️ by [Squareboat](https://squareboat.com) -------------------------------------------------------------------------------- /lib/interfaces/options.ts: -------------------------------------------------------------------------------- 1 | import { ModuleMetadata, Type } from "@nestjs/common/interfaces"; 2 | import { MailmanOptions } from "@squareboat/nest-mailman"; 3 | 4 | /** 5 | * Supported Webhook methods 6 | */ 7 | export enum WebhookSupportMethod { 8 | GET = "GET", 9 | POST = "POST", 10 | } 11 | 12 | /** 13 | * Webhook options 14 | */ 15 | export interface WebhookOptions { 16 | url: string; 17 | method: keyof typeof WebhookSupportMethod; 18 | header?: Record; 19 | requestBuilder?: (payload: any) => Record; 20 | } 21 | 22 | /** 23 | * EyewitnessOptions 24 | * contains all necessary information 25 | */ 26 | export interface EyewitnessOptions { 27 | emails: string[]; 28 | subject?: string; 29 | mailman: MailmanOptions; 30 | webhooks?: WebhookOptions[]; 31 | } 32 | 33 | /** 34 | * EyewitnessOptionsFactory, 35 | * to be used in useClass method in EyewitnessAsyncOptions config 36 | */ 37 | export interface EyewitnessOptionsFactory { 38 | createEyewitnessOptions(): Promise | EyewitnessOptions; 39 | } 40 | 41 | /** 42 | * EyewitnessAsyncOptions, 43 | * to be used for async registration and loading of dynamic configurations 44 | */ 45 | export interface EyewitnessAsyncOptions 46 | extends Pick { 47 | name?: string; 48 | useExisting?: Type; 49 | useClass?: Type; 50 | useFactory?: ( 51 | ...args: any[] 52 | ) => Promise | EyewitnessOptions; 53 | inject?: any[]; 54 | } 55 | -------------------------------------------------------------------------------- /lib/http.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, HttpService } from "@nestjs/common"; 2 | import * as querystring from "query-string"; 3 | 4 | @Injectable() 5 | export class CustomHttpService { 6 | private static httpSerice: HttpService; 7 | constructor(private httpService: HttpService) { 8 | CustomHttpService.httpSerice = httpService; 9 | } 10 | 11 | static makeQueryParam = (payload: Record) => { 12 | let query = 13 | "?" + 14 | Object.keys(payload) 15 | .map((data) => { 16 | return data + "=" + encodeURIComponent(payload[data]); 17 | }) 18 | .join("&"); 19 | 20 | return query; 21 | }; 22 | 23 | static get(httpCallOptions: { 24 | url: string; 25 | payload: Record; 26 | header: Record; 27 | }) { 28 | const { url, payload, header } = httpCallOptions; 29 | return CustomHttpService.httpSerice 30 | .get( 31 | `${url}?${querystring.stringify(payload, { arrayFormat: "bracket" })}`, 32 | { 33 | headers: header, 34 | } 35 | ) 36 | .toPromise() 37 | .then((response: Record) => { 38 | return response; 39 | }) 40 | .catch((error: Record) => { 41 | throw error; 42 | }); 43 | } 44 | 45 | static post(httpCallOptions: { 46 | url: string; 47 | payload: Record | string; 48 | header: Record; 49 | }) { 50 | const { url, payload, header } = httpCallOptions; 51 | return CustomHttpService.httpSerice 52 | .post(url, payload, { headers: header }) 53 | .toPromise() 54 | .then((response: Record) => { 55 | return response; 56 | }) 57 | .catch((error: Record) => { 58 | throw error; 59 | }); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@squareboat/nest-eyewitness", 3 | "version": "1.0.1", 4 | "description": "A simple easy-to-use package to receive error reports directly to your inbox whenever any exception is witnessed 👀 in your NestJS application.", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "keywords": [ 8 | "nestjs-error", 9 | "nestjs-exception", 10 | "nestjs-exception-filters", 11 | "nestjs-exception-reporting", 12 | "nestjs-error-reporting" 13 | ], 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/squareboat/nest-eyewitness.git" 17 | }, 18 | "bugs": { 19 | "url": "https://github.com/squareboat/nest-eyewitness/issues" 20 | }, 21 | "homepage": "https://github.com/squareboat/nest-eyewitness", 22 | "author": "Vinayak Sarawagi ", 23 | "private": false, 24 | "license": "MIT", 25 | "scripts": { 26 | "build": "rm -rf dist && tsc -p tsconfig.json", 27 | "format": "prettier --write \"**/*.ts\"", 28 | "lint": "eslint 'lib/**/*.ts' --fix", 29 | "prepublish:npm": "npm run build", 30 | "publish:npm": "npm publish --access public", 31 | "prepublish:next": "npm run build", 32 | "publish:next": "npm publish --access public --tag next", 33 | "test:e2e": "jest --config ./tests/jest-e2e.json --runInBand", 34 | "test:e2e:dev": "jest --config ./tests/jest-e2e.json --runInBand --watch" 35 | }, 36 | "devDependencies": { 37 | "@nestjs/common": "^7.4.2", 38 | "@nestjs/core": "^7.4.2", 39 | "@types/node": "^14.0.27", 40 | "typescript": "^3.9.7" 41 | }, 42 | "dependencies": { 43 | "@squareboat/nest-mailman": "^0.1.0", 44 | "query-string": "^6.13.1" 45 | }, 46 | "peerDependencies": { 47 | "@nestjs/common": "^6.7.0 || ^7.0.0", 48 | "@nestjs/core": "^6.7.0 || ^7.0.0" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lib/module.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Module, 3 | DynamicModule, 4 | Provider, 5 | Type, 6 | HttpModule, 7 | Inject, 8 | } from "@nestjs/common"; 9 | import { 10 | EyewitnessOptions, 11 | EyewitnessAsyncOptions, 12 | EyewitnessOptionsFactory, 13 | } from "./interfaces"; 14 | import { EYEWITNESS_OPTIONS } from "./provider.map"; 15 | import { EyewitnessService } from "./service"; 16 | import { CustomHttpService } from "./http"; 17 | import { MailmanModule } from "@squareboat/nest-mailman"; 18 | import { MailmanConfigFactory } from "./mailmanConfig"; 19 | 20 | @Module({ 21 | imports: [HttpModule], 22 | providers: [EyewitnessService, CustomHttpService, MailmanConfigFactory], 23 | exports: [EyewitnessService], 24 | }) 25 | export class EyewitnessModule { 26 | /** 27 | * Register options 28 | * @param options 29 | */ 30 | static register(options: EyewitnessOptions): DynamicModule { 31 | return { 32 | global: true, 33 | module: EyewitnessModule, 34 | imports: [ 35 | MailmanModule.registerAsync({ 36 | useClass: MailmanConfigFactory, 37 | }), 38 | ], 39 | exports: [MailmanConfigFactory], 40 | providers: [ 41 | EyewitnessService, 42 | MailmanConfigFactory, 43 | { 44 | provide: EYEWITNESS_OPTIONS, 45 | useValue: options, 46 | }, 47 | ], 48 | }; 49 | } 50 | 51 | /** 52 | * Register Async Options 53 | */ 54 | static registerAsync(options: EyewitnessAsyncOptions): DynamicModule { 55 | return { 56 | global: true, 57 | module: EyewitnessModule, 58 | providers: [ 59 | MailmanConfigFactory, 60 | this.createStorageOptionsProvider(options), 61 | EyewitnessService, 62 | ], 63 | exports: [MailmanConfigFactory], 64 | }; 65 | } 66 | 67 | private static createStorageOptionsProvider( 68 | options: EyewitnessAsyncOptions 69 | ): Provider { 70 | if (options.useFactory) { 71 | return { 72 | provide: EYEWITNESS_OPTIONS, 73 | useFactory: options.useFactory, 74 | inject: options.inject || [], 75 | }; 76 | } 77 | 78 | const inject = [ 79 | (options.useClass || options.useExisting) as Type, 80 | ]; 81 | 82 | return { 83 | provide: EYEWITNESS_OPTIONS, 84 | useFactory: async (optionsFactory: EyewitnessOptionsFactory) => 85 | await optionsFactory.createEyewitnessOptions(), 86 | inject, 87 | }; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /lib/service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | EyewitnessOptions, 3 | WebhookOptions, 4 | WebhookSupportMethod, 5 | } from "./interfaces"; 6 | import { CustomHttpService } from "./http"; 7 | import { Injectable, Inject, ArgumentsHost } from "@nestjs/common"; 8 | import { EYEWITNESS_OPTIONS } from "./provider.map"; 9 | import { Mailman } from "@squareboat/nest-mailman"; 10 | import { TEMPLATE } from "./resources/template"; 11 | 12 | @Injectable() 13 | export class EyewitnessService { 14 | private static config: EyewitnessOptions; 15 | constructor(@Inject(EYEWITNESS_OPTIONS) config: EyewitnessOptions) { 16 | EyewitnessService.config = config; 17 | } 18 | 19 | static getConfig(): EyewitnessOptions { 20 | return EyewitnessService.config; 21 | } 22 | 23 | static async alert(exception: any, host: ArgumentsHost): Promise { 24 | const { emails, subject, webhooks } = EyewitnessService.config; 25 | const payload = this.buildPayload(exception, host); 26 | const finalSubject = (subject || ":error Error Captured").replace( 27 | ":error", 28 | payload.exception.name 29 | ); 30 | 31 | await Mailman.init() 32 | .to(emails) 33 | .subject(finalSubject) 34 | .template(TEMPLATE, payload) 35 | .send(); 36 | 37 | /** 38 | * Run webhooks mentioned in the config 39 | */ 40 | if (Array.isArray(webhooks) && webhooks.length > 0) { 41 | webhooks.forEach((e) => { 42 | EyewitnessService.handleAPICall(e, payload); 43 | }); 44 | } 45 | 46 | return; 47 | } 48 | 49 | static handleAPICall( 50 | webhookOptions: WebhookOptions, 51 | defaultPayload: Record 52 | ) { 53 | const { url, method, header } = webhookOptions; 54 | let httpCallOptions = { 55 | url: url, 56 | payload: defaultPayload, 57 | header: header || {}, 58 | }; 59 | 60 | if (webhookOptions.requestBuilder) { 61 | httpCallOptions.payload = webhookOptions.requestBuilder(defaultPayload); 62 | } 63 | 64 | if (method == WebhookSupportMethod.GET) { 65 | return CustomHttpService.get(httpCallOptions); 66 | } 67 | return CustomHttpService.post(httpCallOptions); 68 | } 69 | 70 | static buildPayload( 71 | exception: any, 72 | host: ArgumentsHost 73 | ): Record { 74 | const ctx = host.switchToHttp(); 75 | const request = ctx.getRequest(); 76 | 77 | return { 78 | exception: { 79 | name: exception.constructor.name, 80 | message: exception.message, 81 | stack: exception.stack.toString(), 82 | }, 83 | request: { 84 | timestamp: new Date().toString(), 85 | headers: JSON.stringify(request.headers), 86 | payload: JSON.stringify({ 87 | ...request.query, 88 | ...request.body, 89 | ...request.params, 90 | }), 91 | url: 92 | request.protocol + "://" + request.get("host") + request.originalUrl, 93 | }, 94 | }; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 15 | do not have permission to do that, you may request the second reviewer to merge it for you. 16 | 17 | ## Code of Conduct 18 | 19 | ### Our Pledge 20 | 21 | In the interest of fostering an open and welcoming environment, we as 22 | contributors and maintainers pledge to making participation in our project and 23 | our community a harassment-free experience for everyone, regardless of age, body 24 | size, disability, ethnicity, gender identity and expression, level of experience, 25 | nationality, personal appearance, race, religion, or sexual identity and 26 | orientation. 27 | 28 | ### Our Standards 29 | 30 | Examples of behavior that contributes to creating a positive environment 31 | include: 32 | 33 | * Using welcoming and inclusive language 34 | * Being respectful of differing viewpoints and experiences 35 | * Gracefully accepting constructive criticism 36 | * Focusing on what is best for the community 37 | * Showing empathy towards other community members 38 | 39 | Examples of unacceptable behavior by participants include: 40 | 41 | * The use of sexualized language or imagery and unwelcome sexual attention or 42 | advances 43 | * Trolling, insulting/derogatory comments, and personal or political attacks 44 | * Public or private harassment 45 | * Publishing others' private information, such as a physical or electronic 46 | address, without explicit permission 47 | * Other conduct which could reasonably be considered inappropriate in a 48 | professional setting 49 | 50 | ### Our Responsibilities 51 | 52 | Project maintainers are responsible for clarifying the standards of acceptable 53 | behavior and are expected to take appropriate and fair corrective action in 54 | response to any instances of unacceptable behavior. 55 | 56 | Project maintainers have the right and responsibility to remove, edit, or 57 | reject comments, commits, code, wiki edits, issues, and other contributions 58 | that are not aligned to this Code of Conduct, or to ban temporarily or 59 | permanently any contributor for other behaviors that they deem inappropriate, 60 | threatening, offensive, or harmful. 61 | 62 | ### Scope 63 | 64 | This Code of Conduct applies both within project spaces and in public spaces 65 | when an individual is representing the project or its community. Examples of 66 | representing a project or community include using an official project e-mail 67 | address, posting via an official social media account, or acting as an appointed 68 | representative at an online or offline event. Representation of a project may be 69 | further defined and clarified by project maintainers. 70 | 71 | ### Enforcement 72 | 73 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 74 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 75 | complaints will be reviewed and investigated and will result in a response that 76 | is deemed necessary and appropriate to the circumstances. The project team is 77 | obligated to maintain confidentiality with regard to the reporter of an incident. 78 | Further details of specific enforcement policies may be posted separately. 79 | 80 | Project maintainers who do not follow or enforce the Code of Conduct in good 81 | faith may face temporary or permanent repercussions as determined by other 82 | members of the project's leadership. 83 | 84 | ### Attribution 85 | 86 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 87 | available at [http://contributor-covenant.org/version/1/4][version] 88 | 89 | [homepage]: http://contributor-covenant.org 90 | [version]: http://contributor-covenant.org/version/1/4/ 91 | --------------------------------------------------------------------------------