Skip to content

Commit

Permalink
Add utils for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
manelcecs authored and Pl217 committed Mar 19, 2024
1 parent 24308fb commit 844a58a
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 1 deletion.
52 changes: 52 additions & 0 deletions tests/testContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import v4Models, { type Database } from '@unocha/hpc-api-core/src/db';
import { type ApolloServer } from 'apollo-server-hapi';
import type Knex from 'knex';
import { createDbConnection } from './utils/connection';
import createApolloTestServer from './utils/server';

interface IContext {
models: Database;
conn: Knex;
apolloTestServer: ApolloServer;
}

export default class ContextProvider implements IContext {
private static _instance: ContextProvider;

models: Database;
conn: Knex;
apolloTestServer: ApolloServer;

private constructor() {
this.models = {} as Database;
this.conn = {} as Knex;
this.apolloTestServer = {} as ApolloServer;
}

public static get Instance(): ContextProvider {
if (this._instance) {
return this._instance;
}
this._instance = new ContextProvider();
return this._instance;
}

public async setUpContext(): Promise<void> {
const connection = await this.createDbTestConnection();
this.conn = connection;
this.models = v4Models(this.conn);
this.apolloTestServer = await createApolloTestServer(
this.conn,
this.models
);
}

private async createDbTestConnection(): Promise<Knex<any, unknown[]>> {
return await createDbConnection({
host: 'localhost',
port: 6432,
user: 'postgres',
database: 'hpc-test',
});
}
}
33 changes: 33 additions & 0 deletions tests/utils/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as t from 'io-ts';
import Knex from 'knex';

const CONFIG = t.type({
host: t.string,
port: t.number,
user: t.string,
database: t.string,
});

/**
* Initialize a new Postgres provider
*/
export async function createDbConnection(connection: t.TypeOf<typeof CONFIG>) {
const knex = Knex({
client: 'pg',
connection,
pool: { min: 0, max: 10, idleTimeoutMillis: 500 },
debug: false,
});

// Verify the connection before proceeding
try {
await knex.raw('SELECT now()');

return knex;
} catch (error) {
console.log(error);
throw new Error(
'Unable to connect to Postgres via Knex. Ensure a valid connection.'
);
}
}
62 changes: 62 additions & 0 deletions tests/utils/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as Hapi from '@hapi/hapi';
import { type Database } from '@unocha/hpc-api-core/src/db';
import { ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';
import {
ApolloServer,
ApolloServerPluginStopHapiServer,
} from 'apollo-server-hapi';
import type Knex from 'knex';
import PlatformPath from 'node:path';
import 'reflect-metadata';
import { buildSchema } from 'type-graphql';
import { Container } from 'typedi';
import { CONFIG } from '../../config';
import { getTokenFromRequest } from '../../src/common-libs/auth';

export default async function createApolloTestServer(
connection: Knex,
models: Database,
auth?: boolean
) {
const schema = await buildSchema({
resolvers: [
PlatformPath.join(
__dirname,
'../../src/domain-services/**/resolver.{ts,js}'
),
],
container: Container, // Register the 3rd party IOC container
});

const hapiServer = Hapi.server({
port: CONFIG.httpPort,
app: {
config: CONFIG,
connection,
},
});

const apolloServerConfig = {
connection,
models,
config: CONFIG,
};

return new ApolloServer({
schema,
context: ({ request }: { request: Hapi.Request }) => ({
...apolloServerConfig,
token: auth ? getTokenFromRequest(request) : undefined,
}),
plugins: [
ApolloServerPluginStopHapiServer({ hapiServer }),
/**
* Don't use sandbox explorer hosted on https://studio.apollographql.com
* but use local sandbox instead. Even though GraphQL playground is
* retired, it is much more useful for local development
* https://github.com/graphql/graphql-playground/issues/1143
*/
ApolloServerPluginLandingPageGraphQLPlayground(),
],
});
}
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"src/**/*.js",
"start.js",
"bin",
"jest.config.ts"
"jest.config.ts",
"tests/**/*.ts"
],
"exclude": ["node_modules"]
}

0 comments on commit 844a58a

Please sign in to comment.