Gathering detailed insights and metrics for @alphaapps/nestjs-common
Gathering detailed insights and metrics for @alphaapps/nestjs-common
Gathering detailed insights and metrics for @alphaapps/nestjs-common
Gathering detailed insights and metrics for @alphaapps/nestjs-common
npm install @alphaapps/nestjs-common
Typescript
Module System
Node Version
NPM Version
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Latest Version
3.0.34
Package Id
@alphaapps/nestjs-common@3.0.34
Unpacked Size
216.28 kB
Size
46.29 kB
File Count
123
NPM Version
lerna/3.22.1/node@v20.7.0+arm64 (darwin)
Node Version
20.7.0
Published on
Feb 25, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
16
2
A set of decorators and services that are commonly used in our applications.
1npm install @alphaapps/nestjs-common
GetUser
: Used in controllers to get the current authenticated user.1export default class UserController { 2 getMe(@GetUser() user: User): User { 3 return { user }; 4 } 5}
InjectSentry
: Injects Sentry service so it can be called.CrudWrapperInterceptor
: User to wrap the response of crud APIs with data
key.UserLanguageSetterInterceptor
: Updates the language
, devicePlatform
& appVersion
of the user using values passed in headers in the request.LocalizationSetter
: Used to update response with the correct language.WinstonLoggingInterceptor
: Logs every request to winston
rewriteUrls
: A middleware for rewriting URLs. This is useful when want to add a param to the request URL without forcing the API consumer to do it.1export default class AppModule implements NestModule { 2 configure(consumer: MiddlewareConsumer): void { 3 consumer 4 .apply(rewrite([{ 5 method: 'GET', 6 from: '/notifications', 7 to: '/notifications?limit=100&sort=createdAt,DESC' 8 }])) 9 .forRoutes({ 10 path: '*', 11 method: RequestMethod.ALL 12 }); 13 } 14}
ExceptionsFilter
: An exception filter that catches all exceptions and check if these are business errors (i.e. User not verified, unique violations) and print them in a pretty way, when an exception is unknown (not one of our known errors) it reports it to Sentry.winston
.Every error in the app must be an instance of AlphaError
class.
Application errors must be like this:
1import { errors } from '@alphaapps/nestjs-common'; 2import _ from 'lodash'; 3 4const localErrors = { 5 users: { 6 invalidEmail: { 7 code: 311, 8 message: 'invalid_email_string', 9 statusCode: 400 10 }, 11 }, 12 files: { 13 conflictingFiles: { 14 code: 400, 15 message: 'conflicting_files', 16 statusCode: 400 17 } 18 }, 19}; 20 21export default _.merge(errors, localErrors);
Then every error should be fired like this: throw new AlphaError('users.invalidEmail')
These errors must be provided in the AppModule
so the ExceptionsFilter
can identify them.
1@Module({ 2 providers: [{ 3 provide: APP_INTERCEPTOR, 4 useClass: WinstonLoggingInterceptor 5 }, { 6 provide: APP_FILTER, 7 useClass: ExceptionsFilter 8 }, { 9 provide: ERRORS_TOKEN, 10 useValue: Errors 11 }] 12}) 13export default class AppModule {}
SentryService
: A service to encapsulate Sentry SDK with two methods captureException
& captureEvent
@InjectSentry
decorator.SequelizeCrudService
: A CRUD service for Sequelize ORM. More info can be viewed at crud github repogetMany
method calls 2 sub methods createBuilder
& executeQuery
to enable some customization in the extending service.count
in getMany
function the many associations to get correct results.getMany
uses modelFindAll
& modelCount
methods to enable more customisation.FirebaseService
: Encapsulation for firebase push notification service.MandrillService
: Encapsulation for Mandrill email service.SesService
: Encapsulation for SES email service.TwilioService
: Encapsulation for Twilio SMS service.This service is used to query logs stored on disk and it's super useful in development environments.
By default when using WinstonLoggingInterceptor
and ExceptionsFilter
all our requests and failed responses are saved via winston
logging lib. So in AppModule
we define the following transports
1const env = process.env.NODE_ENV || 'development'; 2const winstonTransports: Transport[] = [ 3 new winston.transports.Console({ 4 level: 'debug', 5 log: (info, callback) => { 6 const { 7 level = 'info', http = {}, message, duration 8 } = info; 9 const { method = 'GET', status_code: statusCode = 200 } = http; 10 // eslint-disable-next-line no-console 11 console.log(`${level}: ${method} ${message} [${statusCode}] ${duration ? `${duration / 1000000}ms` : ''}`); 12 return callback(); 13 } 14 }) 15]; 16// only add DatadogTransport if it is configured 17if (config.has('datadog.apiKey')) { 18 winstonTransports.push(new DatadogTransport({ 19 level: 'debug', 20 apiKey: config.get('datadog.apiKey'), 21 host: config.get('datadog.host'), 22 port: config.get('datadog.port'), 23 metadata: { 24 env, 25 host: `/esc/${env}-api`, 26 service: 'api', 27 ddsource: 'winston-datadog-transport' 28 } 29 })); 30} 31else { 32 // if no datadog config is found then add a file transport 33 winstonTransports.push(new winston.transports.DailyRotateFile({ 34 filename: 'logs/%DATE%-all.log', 35 datePattern: 'YYYY-MM-DD', 36 zippedArchive: true, 37 maxSize: '20m', 38 maxFiles: '14d' 39 })); 40} 41@Module({ 42 imports: [ 43 WinstonModule.forRoot({ 44 format: winston.format.json(), 45 transports: winstonTransports 46 }) 47 ] 48}) 49export default class AppModule {}
Basically what we're doing here is using winston
to write our log entries, on production
env where we usually use DataDog
logs are sent there. However, on other envs we save logs to files on disk.
In order to query these logs (the ones stored in files on disk) we use a small cli called log-cli
which is included in the @alphaapps/nestjs-common
package
sami@Samis-MacBook-Pro project % npx log-cli
Usage: log-cli read:logs
Commands:
log-cli read:logs Query logs from winston
Options:
--help Show help [boolean]
--version Show version number [boolean]
--dir Folder where the logs are [string] [default: "./logs"]
--url URL to match [string]
--method Filter by HTTP method
[choices: "get", "post", "put", "patch", "delete"]
--limit Number of records returned [number] [default: 10]
--sort Sort the list [choices: "desc", "asc"] [default: "desc"]
--last Show result from last period [string] [default: "15d"]
--from From date (ISO Date) [string]
--to To date (ISO Date) [string]
--userId Filter by user id [number]
--level Fetch only a specific level
[string] [choices: "debug", "info", "error"]
--status Filter by response status code [number]
Examples:
read:logs npx log-cli read:logs --dir='./logs' --limit=20 --last=2d
--to=2020-03-01T10:00:00
copyright Alpha-Apps@2020
Not enough non-option arguments: got 0, need at least 1
No vulnerabilities found.
No security vulnerabilities found.