Skip to content

Commit

Permalink
Merge pull request #32 from osher-sade/master
Browse files Browse the repository at this point in the history
test(server): added tests for graphql server
  • Loading branch information
osher-sade authored Feb 21, 2019
2 parents c224c9c + 7e80cba commit 2b4ff17
Show file tree
Hide file tree
Showing 10 changed files with 574 additions and 425 deletions.
823 changes: 421 additions & 402 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions src/common/injectable-interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApplicationLogProperties, LoggerConfiguration } from '@enigmatis/polaris-logs';
import { IResolvers } from 'graphql-tools';
import { HeadersConfiguration } from '../http/request/polaris-request-headers';
import { MiddlewaresConfiguration } from '../http/request/polaris-request-headers';
import { PolarisProperties } from '../properties/polaris-properties';

export interface InjectableType {
Expand All @@ -14,8 +14,8 @@ export interface InjectableResolver {
export interface LoggerConfig {
loggerConfiguration: LoggerConfiguration;
}
export interface HeaderConfig {
headersConfiguration: HeadersConfiguration;
export interface MiddlewaresConfig {
middlewaresConfiguration: MiddlewaresConfiguration;
}
export interface PolarisServerConfig {
polarisProperties: PolarisProperties;
Expand Down
6 changes: 3 additions & 3 deletions src/http/request/polaris-request-headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const getHeaders = (candidate: object): PolarisRequestHeaders => {
}
};

export interface HeadersConfiguration {
dataVersion?: boolean;
realityId?: boolean;
export interface MiddlewaresConfiguration {
allowDataVersionMiddleware?: boolean;
allowRealityMiddleware?: boolean;
}
4 changes: 2 additions & 2 deletions src/inversion-of-control/polaris-types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {
HeaderConfig,
InjectableResolver,
InjectableType,
LoggerConfig,
MiddlewaresConfig,
PolarisServerConfig,
} from '../common/injectable-interfaces';
import { PolarisGraphqlLogger } from '../logging/polaris-graphql-logger';
Expand All @@ -16,7 +16,7 @@ export const POLARIS_TYPES = {
PolarisHeadersFactory: Symbol('PolarisHeadersFactory'),
Middleware: Symbol('Middleware'),
PolarisServerConfig: Symbol('PolarisServerConfig'),
HeaderConfig: Symbol('HeaderConfig'),
MiddlewaresConfig: Symbol('MiddlewaresConfig'),
LoggerConfig: Symbol('LoggerConfig'),
InjectableType: Symbol('InjectableType'),
InjectableResolver: Symbol('InjectableResolver'),
Expand Down
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export {
InjectableResolver,
InjectableType,
LoggerConfig,
HeaderConfig,
MiddlewaresConfig,
PolarisServerConfig,
} from './common/injectable-interfaces';
export { polarisContainer } from './inversion-of-control/container-manager';
Expand All @@ -20,4 +20,4 @@ export { RepositoryEntity } from './dal/entities/repository-entity';
export { CommonEntityInterface } from './schema/common/entities/common-entity-interface';
export { PolarisSchemaCreator, SchemaCreator } from './schema/utils/schema-creator';
export { GraphQLServer, PolarisGraphQLServer } from './server/graphql-server';
export { HeadersConfiguration } from './http/request/polaris-request-headers';
export { MiddlewaresConfiguration } from './http/request/polaris-request-headers';
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { isSubEntity, MiddlewareCondition } from './filter-condition';
class FilterDataVersion implements MiddlewareCondition {
shouldBeReturned({ root, context, info }: ResponseMiddlewareParams): boolean {
const dataVersionHeader = context.headers.dataVersion;
return !dataVersionHeader || (!isSubEntity(info) && root.dataVersion > dataVersionHeader);
return (
!dataVersionHeader ||
(!isSubEntity(info) && root.allowDataVersionMiddleware > dataVersionHeader)
);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ResponseMiddlewareParams } from '../middleware';
import { MiddlewareCondition } from './filter-condition';

class FilterSoftDelete implements MiddlewareCondition {
shouldBeReturned({ root, context, info }: ResponseMiddlewareParams): boolean {
return !root.deleted;
}
}

export const SoftDeleteFilter = new FilterSoftDelete();
22 changes: 13 additions & 9 deletions src/middlewares/polaris-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { GraphqlLogger } from '@enigmatis/utills';
import { inject, injectable } from 'inversify';
import { HeaderConfig } from '../common/injectable-interfaces';
import { MiddlewaresConfig } from '../common/injectable-interfaces';
import { isRepositoryEntity } from '../dal/entities/repository-entity';
import { HeadersConfiguration } from '../http/request/polaris-request-headers';
import { MiddlewaresConfiguration } from '../http/request/polaris-request-headers';
import { POLARIS_TYPES } from '../inversion-of-control/polaris-types';
import { GraphqlLogProperties } from '../logging/graphql-log-properties';
import { PolarisContext } from '../server/polaris-context';
import { Middleware, RequestMiddlewareParams, ResponseMiddlewareParams } from './middleware';
import { DataVersionFilter } from './middleware-activation-condition/filter-data-version';
import { RealityIdFilter } from './middleware-activation-condition/filter-realities';
import { SoftDeleteFilter } from './middleware-activation-condition/filter-soft-delete';

@injectable()
export class PolarisMiddleware implements Middleware {
@inject(POLARIS_TYPES.GraphqlLogger) polarisLogger!: GraphqlLogger<PolarisContext>;
headersConfiguration: HeadersConfiguration;
middlewaresConfig: MiddlewaresConfiguration;

constructor(@inject(POLARIS_TYPES.HeaderConfig) headerConfig: HeaderConfig) {
this.headersConfiguration = headerConfig.headersConfiguration;
constructor(@inject(POLARIS_TYPES.MiddlewaresConfig) middlewaresConfig: MiddlewaresConfig) {
this.middlewaresConfig = middlewaresConfig.middlewaresConfiguration;
}

preResolve({ root, info, context, args }: RequestMiddlewareParams): void {
Expand All @@ -41,7 +42,7 @@ export class PolarisMiddleware implements Middleware {
info,
result,
},
this.headersConfiguration,
this.middlewaresConfig,
)
? result
: null;
Expand All @@ -51,11 +52,14 @@ export class PolarisMiddleware implements Middleware {
return resolveResult;
}

shouldBeReturned(params: ResponseMiddlewareParams, headersConfig: HeadersConfiguration) {
shouldBeReturned(params: ResponseMiddlewareParams, middlewaresConfig: MiddlewaresConfiguration) {
return (
!(params.root && isRepositoryEntity(params.root)) ||
((headersConfig.realityId === false || RealityIdFilter.shouldBeReturned(params)) &&
(headersConfig.dataVersion === false || DataVersionFilter.shouldBeReturned(params)))
(SoftDeleteFilter.shouldBeReturned(params) &&
((middlewaresConfig.allowRealityMiddleware === false ||
RealityIdFilter.shouldBeReturned(params)) &&
(middlewaresConfig.allowDataVersionMiddleware === false ||
DataVersionFilter.shouldBeReturned(params))))
);
}

Expand Down
6 changes: 3 additions & 3 deletions src/server/graphql-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ export class PolarisGraphQLServer implements GraphQLServer {
body: ctx.request.body,
};
} catch (e) {
this.polarisLogger.error('headers error', { throwable: e });
this.polarisLogger.error('Headers error', { throwable: e });
throw new Error('Unable to format headers');
}
},
formatError: (error: any) => {
if (error.extensions && error.extensions.code === 'GRAPHQL_VALIDATION_FAILED') {
return error;
} else {
this.polarisLogger.error('apollo server Error', { throwable: error });
this.polarisLogger.error('Apollo server error', { throwable: error });
return new Error('Internal server error');
}
},
Expand All @@ -84,7 +84,7 @@ export class PolarisGraphQLServer implements GraphQLServer {
},
};
this.server = new ApolloServer(config);
if (!this.polarisProperties.endpoint) {
if (this.polarisProperties.endpoint) {
this.server.applyMiddleware({ app, path: this.polarisProperties.endpoint });
} else {
this.server.applyMiddleware({ app });
Expand Down
113 changes: 113 additions & 0 deletions test/server/graphql-server.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { ApolloServer, makeExecutableSchema } from 'apollo-server-koa';
import { applyMiddleware } from 'graphql-middleware';
import 'reflect-metadata';
import { LoggerConfig, PolarisServerConfig } from '../../src/common/injectable-interfaces';
import { PolarisMiddleware } from '../../src/middlewares/polaris-middleware';
import { createMiddleware } from '../../src/middlewares/polaris-middleware-creator';
import { SchemaCreator } from '../../src/schema/utils/schema-creator';
import { PolarisGraphQLServer } from '../../src/server/graphql-server';

const apolloServerMock: { [T in keyof ApolloServer]: any } = {
applyMiddleware: jest.fn(),
} as any;
jest.mock('apollo-server-koa', () => ({
makeExecutableSchema: jest.fn(),
ApolloServer: jest.fn(() => ({
applyMiddleware: apolloServerMock.applyMiddleware,
})),
}));
jest.mock('graphql-middleware', () => ({
applyMiddleware: jest.fn(),
}));
jest.mock('../../src/middlewares/polaris-middleware-creator', () => ({
createMiddleware: jest.fn(),
}));

describe('graphql-server tests', () => {
const schemaCreatorMock: { [T in keyof SchemaCreator]: any } = {
generateSchema: jest.fn(() => ({ def: 'definition', resolvers: jest.fn() })),
} as any;
const loggerConfigMock: { [T in keyof LoggerConfig]: any } = {} as any;
const polarisServerConfigMock: { [T in keyof PolarisServerConfig]: any } = {
polarisProperties: jest.fn(),
} as any;
const polarisMiddlewareMock: { [T in keyof PolarisMiddleware]: any } = {} as any;

test('creating new polaris server - with arguments - generate schema have been called', () => {
const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMock,
[polarisMiddlewareMock],
);

expect(schemaCreatorMock.generateSchema).toHaveBeenCalled();
});

test('creating new polaris server - with arguments - make executable schema have been called with generated typeDefs', () => {
const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMock,
[polarisMiddlewareMock],
);

expect(makeExecutableSchema).toHaveBeenCalledWith(
expect.objectContaining({
typeDefs: schemaCreatorMock.generateSchema().def,
}),
);
});

test('creating new polaris server - with arguments - graphql apply middleware have been called', () => {
const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMock,
[polarisMiddlewareMock],
);

expect(applyMiddleware).toHaveBeenCalled();
});

test('creating new polaris server - with arguments - create middleware have been called number of times as middlewares provided', () => {
const middlewares = [polarisMiddlewareMock, polarisMiddlewareMock, polarisMiddlewareMock];
const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMock,
middlewares,
);

expect(createMiddleware).toHaveBeenCalledTimes(middlewares.length);
});

test('creating new polaris server - with arguments - apollo server constructor have been called', () => {
const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMock,
[polarisMiddlewareMock],
);

expect(ApolloServer).toHaveBeenCalled();
});

test('creating new polaris server - with arguments - apollo server apply middleware have been called with custom path', () => {
const polarisServerConfigMockWithEndpoint: { [T in keyof PolarisServerConfig]: any } = {
polarisProperties: { endpoint: 'test' },
} as any;

const server = new PolarisGraphQLServer(
schemaCreatorMock,
loggerConfigMock,
polarisServerConfigMockWithEndpoint,
[polarisMiddlewareMock],
);
expect(apolloServerMock.applyMiddleware).toHaveBeenCalledWith(
expect.objectContaining({
path: polarisServerConfigMockWithEndpoint.polarisProperties.endpoint,
}),
);
});
});

0 comments on commit 2b4ff17

Please sign in to comment.