Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add request context to server service interface. #13

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions example/js/exampleApiServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ function parseBoolean(value) {
return undefined;
}

export function createApp(service) {
export function createApp(serviceOrFactory) {
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const getService = typeof serviceOrFactory === 'function' ? serviceOrFactory : () => serviceOrFactory;

/** Gets widgets. */
app.get('/widgets', function (req, res, next) {
const request = {};
Expand All @@ -58,7 +60,7 @@ export function createApp(service) {
request.minPrice = parseFloat(req.query['minPrice']);
}

return service.getWidgets(request)
return getService(req, res).getWidgets(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down Expand Up @@ -87,7 +89,7 @@ export function createApp(service) {
const request = {};
request.widget = req.body;

return service.createWidget(request)
return getService(req, res).createWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -111,7 +113,7 @@ export function createApp(service) {
request.id = req.params.id;
request.ifNoneMatch = req.header('If-None-Match');

return service.getWidget(request)
return getService(req, res).getWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down Expand Up @@ -141,7 +143,7 @@ export function createApp(service) {
const request = {};
request.id = req.params.id;

return service.deleteWidget(request)
return getService(req, res).deleteWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -164,7 +166,7 @@ export function createApp(service) {
request.ops = req.body.ops;
request.weight = req.body.weight;

return service.editWidget(request)
return getService(req, res).editWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -191,7 +193,7 @@ export function createApp(service) {
const request = {};
request.ids = req.body;

return service.getWidgetBatch(request)
return getService(req, res).getWidgetBatch(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -217,7 +219,7 @@ export function createApp(service) {
const request = {};
request.id = req.params.id;

return service.getWidgetWeight(request)
return getService(req, res).getWidgetWeight(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -240,7 +242,7 @@ export function createApp(service) {
const request = {};
request.key = req.params.key;

return service.getPreference(request)
return getService(req, res).getPreference(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -264,7 +266,7 @@ export function createApp(service) {
request.key = req.params.key;
request.value = req.body;

return service.setPreference(request)
return getService(req, res).setPreference(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -286,7 +288,7 @@ export function createApp(service) {
app.get('/', function (req, res, next) {
const request = {};

return service.getInfo(request)
return getService(req, res).getInfo(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -308,7 +310,7 @@ export function createApp(service) {
app.post('/notRestful', function (req, res, next) {
const request = {};

return service.notRestful(request)
return getService(req, res).notRestful(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -328,7 +330,7 @@ export function createApp(service) {
const request = {};
request.sink = req.body.sink;

return service.kitchen(request)
return getService(req, res).kitchen(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down
30 changes: 17 additions & 13 deletions example/ts/src/exampleApiServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { IServiceResult, IServiceError } from 'facility-core';
import { IExampleApi, IGetWidgetsRequest, IGetWidgetsResponse, ICreateWidgetRequest, ICreateWidgetResponse, IGetWidgetRequest, IGetWidgetResponse, IDeleteWidgetRequest, IDeleteWidgetResponse, IEditWidgetRequest, IEditWidgetResponse, IGetWidgetBatchRequest, IGetWidgetBatchResponse, IGetWidgetWeightRequest, IGetWidgetWeightResponse, IGetPreferenceRequest, IGetPreferenceResponse, ISetPreferenceRequest, ISetPreferenceResponse, IGetInfoRequest, IGetInfoResponse, INotRestfulRequest, INotRestfulResponse, IKitchenRequest, IKitchenResponse, IWidget, IWidgetJob, IPreference, IObsoleteData, IKitchenSink } from './exampleApiTypes';
export * from './exampleApiTypes';

type ServiceFactory<TService> = (req: express.Request, res: express.Response) => TService;

const standardErrorCodes: { [code: string]: number } = {
'notModified': 304,
'invalidRequest': 400,
Expand All @@ -32,11 +34,13 @@ function parseBoolean(value: string | undefined) {
return undefined;
}

export function createApp(service: IExampleApi): express.Application {
export function createApp(serviceOrFactory: IExampleApi | ServiceFactory<IExampleApi>): express.Application {
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const getService: ServiceFactory<IExampleApi> = typeof serviceOrFactory === 'function' ? serviceOrFactory : () => serviceOrFactory;

/** Gets widgets. */
app.get('/widgets', function (req, res, next) {
const request: IGetWidgetsRequest = {};
Expand All @@ -59,7 +63,7 @@ export function createApp(service: IExampleApi): express.Application {
request.minPrice = parseFloat(req.query['minPrice']);
}

return service.getWidgets(request)
return getService(req, res).getWidgets(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down Expand Up @@ -88,7 +92,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: ICreateWidgetRequest = {};
request.widget = req.body;

return service.createWidget(request)
return getService(req, res).createWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -112,7 +116,7 @@ export function createApp(service: IExampleApi): express.Application {
request.id = req.params.id;
request.ifNoneMatch = req.header('If-None-Match');

return service.getWidget(request)
return getService(req, res).getWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down Expand Up @@ -142,7 +146,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: IDeleteWidgetRequest = {};
request.id = req.params.id;

return service.deleteWidget(request)
return getService(req, res).deleteWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -165,7 +169,7 @@ export function createApp(service: IExampleApi): express.Application {
request.ops = req.body.ops;
request.weight = req.body.weight;

return service.editWidget(request)
return getService(req, res).editWidget(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -192,7 +196,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: IGetWidgetBatchRequest = {};
request.ids = req.body;

return service.getWidgetBatch(request)
return getService(req, res).getWidgetBatch(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -218,7 +222,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: IGetWidgetWeightRequest = {};
request.id = req.params.id;

return service.getWidgetWeight(request)
return getService(req, res).getWidgetWeight(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -241,7 +245,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: IGetPreferenceRequest = {};
request.key = req.params.key;

return service.getPreference(request)
return getService(req, res).getPreference(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -265,7 +269,7 @@ export function createApp(service: IExampleApi): express.Application {
request.key = req.params.key;
request.value = req.body;

return service.setPreference(request)
return getService(req, res).setPreference(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -287,7 +291,7 @@ export function createApp(service: IExampleApi): express.Application {
app.get('/', function (req, res, next) {
const request: IGetInfoRequest = {};

return service.getInfo(request)
return getService(req, res).getInfo(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -309,7 +313,7 @@ export function createApp(service: IExampleApi): express.Application {
app.post('/notRestful', function (req, res, next) {
const request: INotRestfulRequest = {};

return service.notRestful(request)
return getService(req, res).notRestful(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand All @@ -329,7 +333,7 @@ export function createApp(service: IExampleApi): express.Application {
const request: IKitchenRequest = {};
request.sink = req.body.sink;

return service.kitchen(request)
return getService(req, res).kitchen(request)
.then(result => {
if (result.error) {
const status = result.error.code && standardErrorCodes[result.error.code] || 500;
Expand Down
54 changes: 50 additions & 4 deletions example/ts/test/exampleApiServerTests.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { createHttpClient } from '../src/exampleApi';
import { createApp } from '../src/exampleApiServer';
import { IServiceResult, IServiceError } from 'facility-core';
import { IServiceResult, IServiceError, IHttpClientOptions, HttpClientUtility } from 'facility-core';
import { IExampleApi, IGetWidgetsRequest, IGetWidgetsResponse, ICreateWidgetRequest, ICreateWidgetResponse, IGetWidgetRequest, IGetWidgetResponse, IDeleteWidgetRequest, IDeleteWidgetResponse, IEditWidgetRequest, IEditWidgetResponse, IGetWidgetBatchRequest, IGetWidgetBatchResponse, IGetWidgetWeightRequest, IGetWidgetWeightResponse, IGetPreferenceRequest, IGetPreferenceResponse, ISetPreferenceRequest, ISetPreferenceResponse, IGetInfoRequest, IGetInfoResponse, INotRestfulRequest, INotRestfulResponse, IKitchenRequest, IKitchenResponse, IWidget, IWidgetJob, IPreference, IObsoleteData, IKitchenSink } from '../src/exampleApiTypes';
import * as crypto from 'crypto';
import { expect, should } from 'chai';
import * as express from 'express';
import * as http from 'http';
import fetch from 'node-fetch';

Expand All @@ -16,6 +17,14 @@ function md5(data: string | Buffer): string {
}

class ExampleApi implements IExampleApi {
private req?: express.Request;
private res?: express.Response;

constructor(req?: express.Request, res?: express.Response) {
this.req = req;
this.res = res;
}

getWidgets(request: IGetWidgetsRequest): Promise<IServiceResult<IGetWidgetsResponse>> {
throw new Error('Method not implemented.');
}
Expand Down Expand Up @@ -104,8 +113,12 @@ class ExampleApi implements IExampleApi {
throw new Error('Method not implemented.');
}

getInfo(request: IGetInfoRequest): Promise<IServiceResult<IGetInfoResponse>> {
throw new Error('Method not implemented.');
async getInfo(request: IGetInfoRequest): Promise<IServiceResult<IGetInfoResponse>> {
return {
value: {
name: this.req!.header('x-name')
}
};
}

notRestful(request: INotRestfulRequest): Promise<IServiceResult<INotRestfulResponse>> {
Expand All @@ -117,7 +130,7 @@ class ExampleApi implements IExampleApi {
}
}

describe('createApp', () => {
describe('singleton service', () => {

const app = createApp(new ExampleApi());
let server: http.Server;
Expand Down Expand Up @@ -212,3 +225,36 @@ describe('createApp', () => {
expect(result.error!.code).to.equal('invalidRequest');
});
});

function fetchWithHeaders(headers: object): HttpClientUtility.IFetch {
return async (uri, request) => fetch(uri, { ...request, headers: { ...request.headers, ...headers }});
}

describe('create service per request', () => {

const app = createApp((req, res) => new ExampleApi(req, res));
let server: http.Server;
let client: IExampleApi;

before(() => {
server = app.listen(0, '127.0.0.1', () => {
const { address, port } = server.address();

client = createHttpClient({
fetch: fetchWithHeaders({ 'x-name': 'Steve' }),
baseUri: `http://${address}:${port}`
});
});
});

after(() => {
server.close();
})

it('get info with header', async () => {
const result = await client.getInfo({});

expect(result.value).to.be.ok;
expect(result.value!.name).to.equal('Steve');
});
});
9 changes: 7 additions & 2 deletions src/Facility.CodeGen.JavaScript/JavaScriptGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,8 @@ protected override CodeGenOutput GenerateOutputCore(ServiceInfo service)
{
code.WriteLine($"import {{ {string.Join(", ", typeNames)} }} from './{Uncapitalize(moduleName)}Types';");
code.WriteLine($"export * from './{Uncapitalize(moduleName)}Types';");
code.WriteLine();
code.WriteLine("type ServiceFactory<TService> = (req: express.Request, res: express.Response) => TService;");
}

// TODO: export this from facility-core
Expand Down Expand Up @@ -338,12 +340,15 @@ protected override CodeGenOutput GenerateOutputCore(ServiceInfo service)
}

code.WriteLine();
using (code.Block("export function createApp(service" + IfTypeScript($": I{capModuleName}") + ")" + IfTypeScript(": express.Application") + " {", "}"))
using (code.Block("export function createApp(serviceOrFactory" + IfTypeScript($": I{capModuleName} | ServiceFactory<I{capModuleName}>") + ")" + IfTypeScript(": express.Application") + " {", "}"))
{
code.WriteLine("const app = express();");
code.WriteLine("app.use(bodyParser.json());");
code.WriteLine("app.use(bodyParser.urlencoded({ extended: true }));");

code.WriteLine();
code.WriteLine("const getService" + IfTypeScript($": ServiceFactory<I{capModuleName}>") + " = typeof serviceOrFactory === 'function' ? serviceOrFactory : () => serviceOrFactory;");

foreach (var httpMethodInfo in httpServiceInfo.Methods)
{
string methodName = httpMethodInfo.ServiceMethod.Name;
Expand Down Expand Up @@ -385,7 +390,7 @@ protected override CodeGenOutput GenerateOutputCore(ServiceInfo service)
}

code.WriteLine();
code.WriteLine($"return service.{methodName}(request)");
code.WriteLine($"return getService(req, res).{methodName}(request)");

using (code.Indent())
{
Expand Down