Skip to content

Commit

Permalink
fix(common): refactoring adapter and centralize code
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Apr 11, 2022
1 parent 7b735ba commit 79759b7
Show file tree
Hide file tree
Showing 37 changed files with 541 additions and 428 deletions.
4 changes: 2 additions & 2 deletions .nycrc
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@
"lcov"
],
"check-coverage": true,
"lines": 99.52,
"lines": 99.48,
"statements": 98.48,
"functions": 98.83,
"functions": 98.73,
"branches": 86.66
}
2 changes: 1 addition & 1 deletion packages/graphql/apollo/src/interfaces/ApolloSettings.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {ApolloServerBase, Config, ApolloServerPluginLandingPageGraphQLPlaygroundOptions} from "apollo-server-core";

export type ApolloMiddlewareOptions = Record<string, any>;
export type ApolloServer = ApolloServerBase & {applyMiddleware(settings: ApolloMiddlewareOptions): any};
export type ApolloServer = ApolloServerBase & {getMiddleware(settings: ApolloMiddlewareOptions): any};
export type ApolloCustomServerCB = (config: ApolloConfig) => ApolloServer;
export type ApolloConfig = Config;

Expand Down
15 changes: 8 additions & 7 deletions packages/graphql/apollo/src/services/ApolloService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {Constant, Inject, Service} from "@tsed/di";
import {Logger} from "@tsed/logger";
import {PlatformApplication} from "@tsed/common";
import {PlatformAdapter, PlatformApplication} from "@tsed/common";
import type {Config} from "apollo-server-core";
import {
ApolloServerBase,
Expand Down Expand Up @@ -36,7 +36,7 @@ export class ApolloService {
> = new Map();

@Inject()
private app: PlatformApplication;
private adapter: PlatformAdapter;

@Inject(Http.Server)
private httpServer: Http.Server | null;
Expand Down Expand Up @@ -71,11 +71,12 @@ export class ApolloService {

await server.start();

await server.applyMiddleware({
path: settings.path,
...middlewareOptions,
app: this.app.raw
});
this.adapter.useMiddleware(
server.getMiddleware({
path: settings.path,
...middlewareOptions
})
);

return server;
}
Expand Down
5 changes: 3 additions & 2 deletions packages/graphql/typegraphql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"build:cjs": "tsc --build tsconfig.compile.json",
"build:esm": "tsc --build tsconfig.compile.esm.json",
"barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\" -e \".benchmark.ts\"",
"start": "ts-node -r tsconfig-paths/register test/app/index.ts",
"start:express": "ts-node -r tsconfig-paths/register test/app/index.express.ts",
"start:koa": "ts-node -r tsconfig-paths/register test/app/index.koa.ts",
"test": "cross-env NODE_ENV=test nyc mocha"
},
"dependencies": {
Expand All @@ -40,4 +41,4 @@
"graphql": ">=15.0.0",
"type-graphql": ">=1.0.0"
}
}
}
36 changes: 1 addition & 35 deletions packages/graphql/typegraphql/test/app/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {buildContext} from "graphql-passport";
import methodOverride from "method-override";
import {resolve} from "path";
import {User} from "./graphql/auth/User";
import session from "express-session";

const rootDir = resolve(__dirname);

Expand Down Expand Up @@ -44,37 +43,4 @@ const rootDir = resolve(__dirname);
userInfoModel: User
}
})
export class Server {
@Inject()
app: PlatformApplication;

/**
* This method let you configure the middleware required by your application to works.
* @returns {Server}
*/
public $beforeRoutesInit(): void {
this.app
.use(bodyParser.json())
.use(
bodyParser.urlencoded({
extended: true
})
)
.use(cookieParser())
.use(compress({}))
.use(methodOverride())
.use(
session({
secret: "mysecretkey",
resave: true,
saveUninitialized: true,
// maxAge: 36000,
cookie: {
path: "/",
httpOnly: true,
secure: false
}
})
);
}
}
export class Server {}
46 changes: 46 additions & 0 deletions packages/graphql/typegraphql/test/app/index.express.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {$log} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import session from "express-session";
import {Server} from "./Server";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import compress from "compression";
import methodOverride from "method-override";

if (process.env.NODE_ENV !== "test") {
async function bootstrap() {
try {
const platform = await PlatformExpress.bootstrap(Server, {
port: 8082,
middlewares: [
bodyParser.urlencoded({
extended: true
}),
bodyParser.json(),
cookieParser(),
compress({}),
methodOverride(),
session({
secret: "mysecretkey",
resave: true,
saveUninitialized: true,
// maxAge: 36000,
cookie: {
path: "/",
httpOnly: true,
secure: false
}
})
]
});

await platform.listen();
$log.debug("Server initialized");
} catch (er) {
console.error(er);
$log.error(er);
}
}

bootstrap();
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import {$log} from "@tsed/common";
import {PlatformExpress} from "@tsed/platform-express";
import {PlatformKoa} from "@tsed/platform-koa";
import {Server} from "./Server";
import compress from "koa-compress";
import bodyParser from "koa-bodyparser";
import methodOverride from "method-override";

if (process.env.NODE_ENV !== "test") {
async function bootstrap() {
try {
const platform = await PlatformExpress.bootstrap(Server);
const platform = await PlatformKoa.bootstrap(Server, {
middlewares: [compress(), methodOverride(), bodyParser()]
});

await platform.listen();
$log.debug("Server initialized");
Expand Down
73 changes: 73 additions & 0 deletions packages/graphql/typegraphql/test/poc/koa.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import {ApolloServer, gql} from "apollo-server-koa";
import {ApolloServerPluginDrainHttpServer} from "apollo-server-core";
import Koa from "koa";
import KoaRouter from "@koa/router";
import http from "http";

const app = new Koa();
const mainRouter = new KoaRouter();
const httpServer = http.createServer();

async function startApolloServer({typeDefs, resolvers}) {
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [ApolloServerPluginDrainHttpServer({httpServer})]
});

await server.start();

const router = new KoaRouter();
const middlewares = server.getMiddleware({path: "/graphql", app: router});

return {server, middlewares: middlewares};
}

const books = [
{
title: "The Awakening",
author: "Kate Chopin"
},
{
title: "City of Glass",
author: "Paul Auster"
}
];

const resolvers = {
Query: {
books: () => books
}
};

const typeDefs = gql`
# Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
# This "Book" type defines the queryable fields for every book in our data source.
type Book {
title: String
author: String
}
# The "Query" type is special: it lists all of the available queries that
# clients can execute, along with the return type for each. In this
# case, the "books" query returns an array of zero or more Books (defined above).
type Query {
books: [Book]
}
`;

startApolloServer({
typeDefs,
app,
resolvers
}).then(async ({middlewares, server}) => {
app.use(middlewares);
app.listen(3000);

httpServer.on("request", app.callback());

await new Promise((resolve) => httpServer.listen({port: 4000}, resolve));

console.log(`🚀 Server ready at http://localhost:3000${server.graphqlPath}`);
});
6 changes: 6 additions & 0 deletions packages/graphql/typegraphql/test/poc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"scripts": {
"start:koa": "node koa.js"
}
}
7 changes: 5 additions & 2 deletions packages/platform/common/src/builder/PlatformBuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,24 @@ import {join, resolve} from "path";
import Sinon from "sinon";
import {Platform} from "../services/Platform";
import {PlatformBuilder} from "./PlatformBuilder";
import {FakeAdapter} from "../services/FakeAdapter";

const sandbox = Sinon.createSandbox();

describe("PlatformBuilder", () => {
@Controller("/")
class RestCtrl {}

class PlatformCustom implements PlatformAdapter {
class PlatformCustom extends FakeAdapter {
readonly providers = [
{
provide: class Test {}
}
];

constructor(private platform: PlatformBuilder) {}
constructor(private platform: PlatformBuilder) {
super();
}

static create(module: Type<any>, settings: Partial<TsED.Configuration> = {}) {
return PlatformBuilder.create<any, any>(module, {
Expand Down
22 changes: 11 additions & 11 deletions packages/platform/common/src/builder/PlatformBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {PlatformStaticsSettings} from "../config/interfaces/PlatformStaticsSetti
import {getStaticsOptions} from "../utils/getStaticsOptions";
import {Route} from "../interfaces/Route";
import {getConfiguration} from "../utils/getConfiguration";
import type {IncomingMessage, ServerResponse, Server} from "http";
import {PlatformAdapter, PlatformBuilderSettings} from "../interfaces/PlatformAdapter";
import type {IncomingMessage, Server, ServerResponse} from "http";
import {PlatformAdapter, PlatformBuilderSettings} from "../services/PlatformAdapter";
import {importProviders} from "../utils/importProviders";
import {createInjector} from "../utils/createInjector";
import {GlobalAcceptMimesMiddleware} from "../middlewares/GlobalAcceptMimesMiddleware";
Expand All @@ -21,34 +21,34 @@ import type Https from "https";
* @platform
*/
export class PlatformBuilder<App = TsED.Application, Router = TsED.Router> {
public static adapter: Type<PlatformAdapter>;
public static adapter: Type<PlatformAdapter<any, any>>;

readonly name: string = "";
protected startedAt = new Date();
protected current = new Date();

#injector: InjectorService;
#rootModule: Type<any>;
readonly #injector: InjectorService;
readonly #rootModule: Type<any>;
readonly #adapter: PlatformAdapter<App, Router>;
#promise: Promise<this>;
#adapter: PlatformAdapter<App, Router>;
#servers: (() => Promise<Server | Https.Server>)[];
#listeners: (Server | Https.Server)[] = [];

protected constructor(adapter: Type<PlatformAdapter<App, Router>> | undefined, module: Type, settings: Partial<TsED.Configuration>) {
this.#rootModule = module;
const adapterKlass = adapter || PlatformBuilder.adapter;
const adapterKlass: Type<PlatformAdapter<App, Router>> = adapter || (PlatformBuilder.adapter as any);
const name = nameOf(adapterKlass).replace("Platform", "").toLowerCase();

const configuration = getConfiguration(settings, module);
configuration.PLATFORM_NAME = name;
this.name = name;
this.#adapter = new adapterKlass(this);

this.#injector = createInjector({
settings: configuration,
providers: this.#adapter.providers
adapter: adapterKlass,
settings: configuration
});

this.#adapter = this.#injector.get<PlatformAdapter<App, Router>>(PlatformAdapter)!;

this.createHttpServers();

this.#adapter.onInit && this.#adapter.onInit();
Expand Down
4 changes: 2 additions & 2 deletions packages/platform/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ export * from "./interfaces/OnReady";
export * from "./interfaces/OnRequest";
export * from "./interfaces/OnResponse";
export * from "./interfaces/OnRoutesInit";
export * from "./interfaces/PlatformAdapter";
export * from "./interfaces/PlatformRouteOptions";
export * from "./interfaces/ResponseErrorObject";
export * from "./interfaces/Route";
Expand All @@ -53,8 +52,9 @@ export * from "./middlewares/GlobalAcceptMimesMiddleware";
export * from "./middlewares/PlatformAcceptMimesMiddleware";
export * from "./middlewares/PlatformMulterMiddleware";
export * from "./middlewares/bindEndpointMiddleware";
export * from "./services/FakeRawDriver";
export * from "./services/FakeAdapter";
export * from "./services/Platform";
export * from "./services/PlatformAdapter";
export * from "./services/PlatformApplication";
export * from "./services/PlatformHandler";
export * from "./services/PlatformMiddlewaresChain";
Expand Down
21 changes: 0 additions & 21 deletions packages/platform/common/src/interfaces/PlatformAdapter.ts

This file was deleted.

Loading

0 comments on commit 79759b7

Please sign in to comment.