Skip to content

Commit

Permalink
fix: added test server and some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorVoid committed Dec 5, 2019
1 parent e925948 commit 5165c02
Show file tree
Hide file tree
Showing 23 changed files with 662 additions and 91 deletions.
339 changes: 252 additions & 87 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,17 @@
"@enigmatis/polaris-common": "^1.0.9",
"@enigmatis/polaris-graphql-logger": "^1.1.0",
"@enigmatis/polaris-logs": "^2.6.0",
"@enigmatis/polaris-middlewares": "^1.1.0",
"@enigmatis/polaris-middlewares": "^1.1.1",
"@enigmatis/polaris-schema": "^1.0.5",
"@enigmatis/polaris-typeorm": "^1.1.3",
"@enigmatis/polaris-typeorm": "^1.1.4",
"apollo-server-express": "^2.9.12",
"apollo-server-plugin-base": "^0.6.8",
"express": "^4.17.1",
"graphql": "^14.5.8",
"graphql-middleware": "^4.0.2",
"http-status": "^1.4.1",
"ip": "^1.1.5",
"ts-node": "^8.5.4",
"uuid": "^3.3.3"
},
"devDependencies": {
Expand All @@ -81,8 +82,11 @@
"@types/ip": "^1.1.0",
"@types/jest": "^24.0.23",
"@types/uuid": "^3.4.6",
"axios": "^0.19.0",
"graphql-request": "^1.8.2",
"husky": "^3.1.0",
"jest": "24.1.0",
"pg": "^7.14.0",
"prettier": "^1.19.1",
"rimraf": "^3.0.0",
"travis-deploy-once": "^5.0.11",
Expand Down
10 changes: 10 additions & 0 deletions test/integration-tests/test-server/connection-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Connection, ConnectionOptions, createPolarisConnection } from '@enigmatis/polaris-typeorm';
import { polarisGraphQLLogger } from './logger';

export let connection: Connection;
export async function initConnection(connectionOptions: ConnectionOptions) {
connection = await createPolarisConnection(
connectionOptions,
polarisGraphQLLogger.getPolarisLogger() as any,
);
}
23 changes: 23 additions & 0 deletions test/integration-tests/test-server/dal/author.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Column, CommonModel, Entity, OneToMany } from '@enigmatis/polaris-typeorm';
import { Book } from './book';

@Entity()
export class Author extends CommonModel {
@Column()
public firstName: string;

@Column()
public lastName: string;

@OneToMany(
() => Book,
book => book.author,
)
public books: Book[];
constructor(firstName: string, lastName: string, books?: Book[]) {
super();
this.firstName = firstName;
this.lastName = lastName
this.books = books ? books : [];
}
}
20 changes: 20 additions & 0 deletions test/integration-tests/test-server/dal/book.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Column, CommonModel, Entity, ManyToOne } from '@enigmatis/polaris-typeorm';
import { Author } from './author';

@Entity()
export class Book extends CommonModel {
@Column()
public title: string;

@ManyToOne(
() => Author,
author => author.books,
)
public author: Author;

constructor(title: string, author: Author) {
super();
this.title = title;
this.author = author;
}
}
54 changes: 54 additions & 0 deletions test/integration-tests/test-server/data-initalizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { connection } from './connection-manager';
import { Author } from './dal/author';
import { Book } from './dal/book';
import { polarisGraphQLLogger } from './logger';

export async function deleteTables() {
const tables = ['book', 'author', 'dataVersion'];
for (const table of tables) {
if (connection) {
try {
await connection.getRepository(table).query('DELETE FROM "' + table + '";');
} catch (e) {
polarisGraphQLLogger.debug("Couldn't delete table (might never existed)");
}
}
}
}

function getAuthors(): Author[] {
return [new Author('Author', 'First'), new Author('Author', 'Two')];
}

function getBooks(authors: Author[]): Book[] {
return [
new Book('Book1', authors[0]),
new Book('Book2', authors[1]),
new Book('Book3', authors[0]),
new Book('Book4', authors[0]),
new Book('Book5', authors[1]),
];
}

async function createExampleData(authors: Author[], books: Book[]) {
const authorRepo = connection.getRepository(Author);
const bookRepo = connection.getRepository(Book);
await authorRepo.save(authors);
await bookRepo.save([books[0], books[1]]);
connection.manager.queryRunner.data = { requestHeaders: { realityId: 3 } };
await bookRepo.save(books[2]);
connection.manager.queryRunner.data.returnedExtensions = {};
await bookRepo.save(books[3]);
books[4].setDeleted(true);
await bookRepo.save(books[4]);
delete connection.manager.queryRunner.data.requestHeaders;
delete connection.manager.queryRunner.data.returnedExtensions;
}

export async function initializeDatabase() {
await deleteTables();
await connection.synchronize();
const authors: Author[] = getAuthors();
const books: Book[] = getBooks(authors);
await createExampleData(authors, books);
}
14 changes: 14 additions & 0 deletions test/integration-tests/test-server/graphql-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { GraphQLClient } from 'graphql-request';
import * as polarisProperties from './polaris-properties.json';

export const url = `http://localhost:${polarisProperties.port}/${polarisProperties.version}/graphql`;

export const graphQLRequest = async (data: string, headers: any, variables: any = undefined) => {
const graphQLClient = new GraphQLClient(url, { headers });
return graphQLClient.request(data, variables);
};

export const graphqlRawRequest = async (data: string, headers: any, variables: any = undefined) => {
const graphQLClient = new GraphQLClient(url, { headers });
return graphQLClient.rawRequest(data, variables);
};
24 changes: 24 additions & 0 deletions test/integration-tests/test-server/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { LoggerConfiguration, PolarisGraphQLLogger } from '../../../src/index';

export const loggerConfig: LoggerConfiguration = {
loggerLevel: 'debug',
writeToConsole: true,
writeFullMessageToConsole: false,
};

const applicationLogProperties = {
id: 'example',
name: 'example',
component: 'repo',
environment: 'dev',
version: '1',
};

export const polarisGraphQLLogger = new PolarisGraphQLLogger(
{
loggerLevel: 'debug',
writeToConsole: true,
writeFullMessageToConsole: false,
},
applicationLogProperties,
);
37 changes: 37 additions & 0 deletions test/integration-tests/test-server/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { CommonModel, ConnectionOptions, DataVersion } from '@enigmatis/polaris-typeorm';
import { PolarisServer } from '../../../src/index';
import { connection, initConnection } from './connection-manager';
import { initializeDatabase } from './data-initalizer';
import { loggerConfig } from './logger';
import * as polarisProperties from './polaris-properties.json';
import { resolvers } from './schema/resolvers';
import { typeDefs } from './schema/type-defs';

let server: PolarisServer;
const connectionOptions: ConnectionOptions = {
type: 'postgres',
url: process.env.CONNECTION_STRING || '',
entities: [__dirname + '/dal/*.ts', CommonModel, DataVersion],
synchronize: false,
logging: true,
};
const startApp = async () => {
await initConnection(connectionOptions);
await initializeDatabase();
server = new PolarisServer({
typeDefs,
resolvers,
port: polarisProperties.port,
loggerConfiguration: loggerConfig,
connection,
});
await server.start();
};
try {
startApp();
} catch (e) {
if (server) {
server.stop();
}
process.exit(0);
}
8 changes: 8 additions & 0 deletions test/integration-tests/test-server/polaris-properties.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"port": 8082,
"id": "p0laris-ex5mpl3",
"name": "polaris-example",
"version": "v1",
"environment": "environment",
"component": "component"
}
40 changes: 40 additions & 0 deletions test/integration-tests/test-server/schema/resolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Like } from '../../../../src/index';
import { connection } from '../connection-manager';
import { Author } from '../dal/author';
import { Book } from '../dal/book';
import { polarisGraphQLLogger } from '../logger';

export const resolvers = {
Query: {
allBooks: async (): Promise<Book[]> => {
polarisGraphQLLogger.debug("I'm the resolver of all books");
return connection.getRepository(Book).find({ relations: ['author'] });
},
bookByTitle: (parent: any, args: any): Promise<Book[]> => {
return connection.getRepository(Book).find({
where: { title: Like(`%${args.title}%`) },
relations: ['author'],
});
},
authorById: async (parent: any, args: any): Promise<Author | {}> =>
connection.getRepository(Author).findOne({ where: { id: args.id } }) || {},
},
Mutation: {
createAuthor: async (parent: any, args: any): Promise<Author> => {
const authorRepo = connection.getRepository(Author);
const newAuthor = new Author(args.firstName, args.lastName, []);
await authorRepo.save(newAuthor);
return newAuthor;
},
updateBook: async (parent: any, args: any): Promise<Book> => {
const bookRepo = connection.getRepository(Book);
const result = await bookRepo.find({ where: { title: Like(`%${args.title}%`) } });
const bookToUpdate = result.length > 0 ? result[0] : undefined;
if (bookToUpdate) {
bookToUpdate.title = args.newTitle;
await bookRepo.save(bookToUpdate);
}
return bookToUpdate;
},
},
};
37 changes: 37 additions & 0 deletions test/integration-tests/test-server/schema/type-defs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export const typeDefs = `
type Query {
allBooks: [Book]!
authorById(id: String!): Author
bookByTitle(title: String!): [Book]!
}
type Mutation{
createAuthor(firstName: String!, lastName: String!): Author!
updateBook(title: String!, newTitle: String!): Book
}
type Book implements RepositoryEntity {
id: String!
deleted: Boolean!
createdBy: String!
creationTime: DateTime!
lastUpdatedBy: String
lastUpdateTime: DateTime
realityId: Int!
title: String
author: Author
}
type Author implements RepositoryEntity{
id: String!
deleted: Boolean!
createdBy: String!
creationTime: DateTime!
lastUpdatedBy: String
lastUpdateTime: DateTime
realityId: Int!
firstName: String
lastName: String
books: [Book]
}
`;
37 changes: 37 additions & 0 deletions test/integration-tests/test-server/test-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { CommonModel, ConnectionOptions, DataVersion } from '@enigmatis/polaris-typeorm';
import { PolarisServer } from '../../../src';
import { connection, initConnection } from './connection-manager';
import { deleteTables } from './data-initalizer';
import { loggerConfig, polarisGraphQLLogger } from './logger';
import * as polarisProperties from './polaris-properties.json';
import { resolvers } from './schema/resolvers';
import { typeDefs } from './schema/type-defs';

const connectionOptions: ConnectionOptions = {
type: 'postgres',
url: process.env.CONNECTION_STRING || '',
entities: [__dirname + '/dal/*.ts', CommonModel, DataVersion],
synchronize: false,
logging: true,
};

let server: PolarisServer;

export async function startTestServer(): Promise<PolarisServer> {
jest.setTimeout(15000);
await initConnection(connectionOptions);
server = new PolarisServer({
typeDefs,
resolvers,
port: polarisProperties.port,
loggerConfiguration: loggerConfig,
connection,
});
await server.start();
return server;
}

export async function stopTestServer() {
await connection.close();
await server.stop();
}
Loading

0 comments on commit 5165c02

Please sign in to comment.