Skip to content

Commit

Permalink
feat(gql-fastify): implements parser for GraphQL-Fastify
Browse files Browse the repository at this point in the history
Due to the nature of how apollo-server-fastify works, the `getStatus` method is unusable from any of
the previous package implementations. Instead of extending and making this package require
`platform-express` or `platform-fastify` due to how the `req` object is added, all the methods are
re-implemented for ease. Small code duplication to keep the package size low.

fix #15
  • Loading branch information
jmcdo29 committed Apr 18, 2020
1 parent a355f11 commit 7ec49bc
Show file tree
Hide file tree
Showing 6 changed files with 180 additions and 8 deletions.
11 changes: 7 additions & 4 deletions integration/test/gql.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { HttpServer, INestApplication } from '@nestjs/common';
import { ExpressAdapter } from '@nestjs/platform-express';
import { FastifyAdapter } from '@nestjs/platform-fastify';
import {
AbstractInterceptorService,
OgmaInterceptor,
Type,
} from '@ogma/nestjs-module';
import { GraphQLParser } from '@ogma/platform-graphql';
import { GraphQLFastifyParser } from '@ogma/platform-graphql-fastify';
import { GqlModule } from '../src/gql/gql.module';
import {
createTestModule,
Expand All @@ -16,10 +18,11 @@ import {
import { color } from '@ogma/logger';

describe.each`
adapter | server | parser
${new ExpressAdapter()} | ${'GraphQL Express'} | ${GraphQLParser}
adapter | server | parser
${new ExpressAdapter()} | ${'Express'} | ${GraphQLParser}
${new FastifyAdapter()} | ${'Fastify'} | ${GraphQLFastifyParser}
`(
'$server server',
'GraphQL $server server',
({
adapter,
server,
Expand All @@ -34,7 +37,7 @@ describe.each`

beforeAll(async () => {
const modRef = await createTestModule(GqlModule, {
service: serviceOptionsFactory(server),
service: serviceOptionsFactory(`GraphQL ${server}`),
interceptor: {
gql: parser,
},
Expand Down
27 changes: 24 additions & 3 deletions packages/platform-graphql-fastify/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
# `@ogma/platform-graphql-fastify`

> TODO: description
The `GraphQLFastifyParser` parser for the `OgmaInterceptor`. This plugin class parses GraphQL request and response object to be able to successfully log the data about the request. For more information, check out [the @ogma/nestjs-module](../nestjs-module/README.md) documentation.

## Installation

Nothing special, standard `npm i @ogma/platform-graphql-fastify` or `yarn add @ogma/platform-graphql-fastify`

## Usage

This plugin is to be used in the `OgmaInterceptorOptions` portion of the `OgmaModule` during `forRoot` or `forRootAsync` registration. It can be used like so:

```ts
@Module(
OgmaModule.forRoot({
interceptor: {
gql: GraphQLFastifyParser
}
})
)
export class AppModule {}
```
const platformGraphqlFastify = require('@ogma/platform-graphql-fastify');

// TODO: DEMONSTRATE API
> Note: Due to the nature of subscriptions and the data available from the base ones, it is not possible at this time to log what subscriptions are made in the Ogma fashion.
Because the interceptor needs access to the request and response objects, when configuring the `GraphqlModule` from Nest, you need to add the `req` to the GraphQL context. to do this, while configuring the `GraphqlModule`, set the `context` property as such:

```ts
GraphqlModule.forRoot({
context: ({ req }) => ({ req })
});
```
6 changes: 5 additions & 1 deletion packages/platform-graphql-fastify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
"url": "git+https://github.com/jmcdo29/ogma.git"
},
"scripts": {
"test": "echo \"No tests to run\""
"prebuild": "rimraf lib",
"build": "tsc -p tsconfig.build.json",
"postbuild": "mv ./lib/src/* ./lib && rmdir lib/src",
"test": "jest",
"test:cov": "jest --coverage"
},
"bugs": {
"url": "https://github.com/jmcdo29/ogma/issues"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { ExecutionContext, HttpException, Injectable } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AbstractInterceptorService } from '@ogma/nestjs-module';

@Injectable()
export class GraphQLFastifyParser extends AbstractInterceptorService {
getCallerIp(context: ExecutionContext) {
const req = this.getRequest(context);
return req.ips && req.ips.length ? req.ips.join(' ') : req.ip;
}

getCallPoint(context: ExecutionContext) {
const req = this.getRequest(context);
return req.url;
}

getMethod(context: ExecutionContext) {
return this.getContext(context).getInfo().operation.operation;
}

getProtocol(context: ExecutionContext) {
const req = this.getRequest(context);
return `HTTP/${req.httpVersionMajor}.${req.httpVersionMinor}`;
}

getStatus(
context: ExecutionContext,
inColor: boolean,
error?: Error | HttpException,
) {
const status = error ? this.determineStatusFromError(error) : 200;
return inColor ? this.wrapInColor(status) : status.toString();
}

private determineStatusFromError(error: Error | HttpException) {
try {
return (error as HttpException).getStatus();
} catch (err) {
return 500;
}
}

private getContext(context: ExecutionContext): GqlExecutionContext {
return GqlExecutionContext.create(context);
}

private getRequest(context: ExecutionContext) {
return this.getContext(context).getContext().req;
}
}
1 change: 1 addition & 0 deletions packages/platform-graphql-fastify/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './graphql-fastify-interceptor.service';
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { createMock } from '@golevelup/ts-jest';
import { BadRequestException, ExecutionContext } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { GraphQLFastifyParser } from '../src';
import { color } from '@ogma/logger';

const gqlMockFactory = (context: object, info: object) =>
createMock<ExecutionContext>({
getType: () => 'graphql',
getHandler: () => 'query',
getClass: () => 'Test',
getArgs: () => [{}, {}, context, info],
});

const gqlContextMockFactory = (contextMock: any) =>
gqlMockFactory(contextMock, {});

const gqlInfoMockFactory = (infoMock: any) => gqlMockFactory({}, infoMock);

describe('GraphQLFastifyParser', () => {
let parser: GraphQLFastifyParser;

beforeEach(async () => {
const modRef = await Test.createTestingModule({
providers: [GraphQLFastifyParser],
}).compile();
parser = modRef.get(GraphQLFastifyParser);
});

describe('getCallerIp', () => {
it('should get the IP for a single IP', () => {
const mockCtx = gqlContextMockFactory({
req: {
ip: '127.0.0.1',
},
});
expect(parser.getCallerIp(mockCtx)).toBe('127.0.0.1');
});
it('should get the ips for multiple ips', () => {
const mockCtx = gqlContextMockFactory({
req: {
ips: ['0.0.0.0', '127.0.0.1'],
},
});
expect(parser.getCallerIp(mockCtx)).toBe('0.0.0.0 127.0.0.1');
});
});
describe('getCallPoint', () => {
it('should get the call Point', () => {
const mockContext = gqlContextMockFactory({ req: { url: '/graphql' } });
expect(parser.getCallPoint(mockContext)).toBe('/graphql');
});
});
describe('getProtocol', () => {
it('should get the protocol', () => {
const mockCtx = gqlContextMockFactory({
req: {
httpVersionMajor: 1,
httpVersionMinor: 1,
},
});
expect(parser.getProtocol(mockCtx)).toBe('HTTP/1.1');
});
});
describe('getMethod', () => {
it.each`
method
${'query'}
${'mutation'}
`('method: $method', ({ method }: { method: string }) => {
const mockCtx = gqlInfoMockFactory({ operation: { operation: method } });
expect(parser.getMethod(mockCtx)).toBe(method);
});
});
describe('getStatus', () => {
describe.each`
inColor
${true}
${false}
`('color: $inColor', ({ inColor }: { inColor: boolean }) => {
it.each`
error | status
${undefined} | ${inColor ? color.green(200) : '200'}
${new BadRequestException()} | ${inColor ? color.yellow(400) : '400'}
${new Error()} | ${inColor ? color.red(500) : '500'}
`('error: $error, status: $status', ({ error, status }) => {
expect(
parser.getStatus(createMock<ExecutionContext>(), inColor, error),
).toEqual(status);
});
});
});
});

0 comments on commit 7ec49bc

Please sign in to comment.