Skip to content
This repository has been archived by the owner on Jul 2, 2020. It is now read-only.

fix: fix load plugin from app #174

Merged
merged 3 commits into from
May 31, 2020
Merged
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
2 changes: 1 addition & 1 deletion packages/faas/src/starter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export class FaaSStarter implements IFaaSStarter {
});
this.loader.registerHook(PLUGIN_KEY, (key, target) => {
const ctx = target[REQUEST_OBJ_CTX_KEY] || {};
return ctx[key] || this[key];
return ctx[key] || this.webApplication[key];
});

this.loader.registerHook(LOGGER_KEY, (key, target) => {
Expand Down
3 changes: 3 additions & 0 deletions packages/faas/test/fixtures/base-app-inject/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "demo-app"
}
21 changes: 21 additions & 0 deletions packages/faas/test/fixtures/base-app-inject/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { inject, provide, func, FunctionHandler } from '../../../../src';
import { Plugin, App } from '@midwayjs/decorator';
import * as assert from 'assert';

@provide()
@func('index.handler')
export class HelloService implements FunctionHandler {
@inject()
ctx; // context

@App()
app;

@Plugin()
mysql;

handler(event) {
assert(this.app);
return this.ctx.originContext['text'] + event.text + this.mysql.model;
}
}
28 changes: 28 additions & 0 deletions packages/faas/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,32 @@ describe('test/index.test.ts', () => {

assert(data.body === 'ahello555');
});

it('test inject app and plugin', async () => {
const { start } = require('../../serverless-scf-starter/src');
const runtime = await start();
const starter = new FaaSStarter({
baseDir: join(__dirname, './fixtures/base-app-inject'),
applicationAdapter: runtime,
});
// set app
const app = runtime.getApplication();
app.mysql = {
model: '123',
};
await starter.start();
const data = await runtime.asyncEvent(
starter.handleInvokeWrapper('index.handler')
)(
{
text: 'hello',
httpMethod: 'GET',
headers: {},
requestContext: {},
},
{ text: 'a' }
);

assert(data.body === 'ahello123');
});
});
4 changes: 3 additions & 1 deletion packages/serverless-http-parser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
"encodeurl": "^1.0.2",
"escape-html": "^1.0.3",
"koa-compose": "^4.1.0",
"only": "^0.0.2",
"querystring": "^0.2.0",
"statuses": "^1.5.0",
"type-is": "^1.6.18"
},
"devDependencies": {
"midway-bin": "^2.0.0"
"midway-bin": "^2.0.0",
"mm": "^3.2.0"
},
"engines": {
"node": ">= 10"
Expand Down
46 changes: 45 additions & 1 deletion packages/serverless-http-parser/src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ import { context } from './context';
import { request } from './request';
import { response } from './response';
import * as compose from 'koa-compose';
import * as only from 'only';
import { EventEmitter } from 'events';
import { format } from 'util';

export class Application {
export class Application extends EventEmitter {
proxy = false;
subdomainOffset = 2;
proxyIpHeader = 'X-Forwarded-For';
Expand All @@ -15,6 +18,7 @@ export class Application {
response;

constructor(options?) {
super();
options = options || {};
this.context = Object.create(context);
this.request = Object.create(request);
Expand Down Expand Up @@ -67,6 +71,7 @@ export class Application {

callback() {
const fn = compose(this.middleware);
this.on('error', this.onerror);
return (req, res, respond) => {
// if (!this.listenerCount('error')) this.on('error', this.onerror);
const onerror = err => ctx.onerror(err);
Expand All @@ -78,4 +83,43 @@ export class Application {
.catch(onerror);
};
}

/**
* Return JSON representation.
* We only bother showing settings.
*
* @return {Object}
* @api public
*/

toJSON() {
return only(this, ['subdomainOffset', 'proxy', 'env']);
}

/**
* Inspect implementation.
*
* @return {Object}
* @api public
*/

inspect() {
return this.toJSON();
}

/**
* Default error handler.
*
* @param {Error} err
* @api private
*/

onerror(err) {
if (!(err instanceof Error))
throw new TypeError(format('non-error thrown: %j', err));
const msg = err.stack || err.toString();
console.error();
console.error(msg.replace(/^/gm, ' '));
console.error();
}
}
25 changes: 25 additions & 0 deletions packages/serverless-http-parser/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FaaSOriginContext } from '@midwayjs/faas-typings';
import * as util from 'util';

export const context = {
app: null,
req: null,
res: null,
request: null,
Expand Down Expand Up @@ -176,4 +177,28 @@ export const context = {
redirect(url: string, alt?: string) {
return this.response.redirect(url, alt);
},

/**
* util.inspect() implementation, which
* just returns the JSON output.
*
* @return {Object}
* @api public
*/

inspect() {
if (this === context) return this;
return this.toJSON();
},

toJSON() {
return {
request: this.request.toJSON(),
response: this.response.toJSON(),
app: this.app.toJSON(),
req: '<original node req>',
res: '<original node res>',
socket: '<original node socket>',
};
},
};
24 changes: 24 additions & 0 deletions packages/serverless-http-parser/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { is as typeis } from 'type-is';
import * as accepts from 'accepts';
import { FaaSOriginContext } from '@midwayjs/faas-typings';
import * as qs from 'querystring';
import * as only from 'only';

const BODY = Symbol.for('ctx#body');

Expand Down Expand Up @@ -201,4 +202,27 @@ export const request = {
return this.headers[field] || '';
}
},

/**
* Inspect implementation.
*
* @return {Object}
* @api public
*/

inspect() {
if (!this.req) return;
return this.toJSON();
},

/**
* Return JSON representation.
*
* @return {Object}
* @api public
*/

toJSON() {
return only(this, ['method', 'url', 'header']);
},
};
26 changes: 26 additions & 0 deletions packages/serverless-http-parser/src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as statuses from 'statuses';
import { is as typeis } from 'type-is';
import * as encodeUrl from 'encodeurl';
import * as escape from 'escape-html';
import * as only from 'only';

export const response = {
explicitStatus: null,
Expand Down Expand Up @@ -362,5 +363,30 @@ export const response = {
this.body = `Redirecting to ${url}.`;
},

/**
* Inspect implementation.
*
* @return {Object}
* @api public
*/

inspect() {
if (!this.res) return;
const o = this.toJSON();
o.body = this.body;
return o;
},

/**
* Return JSON representation.
*
* @return {Object}
* @api public
*/

toJSON() {
return only(this, ['status', 'message', 'header']);
},

end() {},
};
27 changes: 27 additions & 0 deletions packages/serverless-http-parser/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as assert from 'assert';
import { Application, HTTPRequest, HTTPResponse } from '../src';
import { FaaSHTTPContext } from '@midwayjs/faas-typings';
import * as mm from 'mm';

describe('test http parser', () => {
it('should parser tencent apigw event', () => {
Expand All @@ -11,6 +12,7 @@ describe('test http parser', () => {
);
const res = new HTTPResponse();
const context = app.createContext(req, res);
assert(context.toJSON().request);

// alias
assert(context.req !== context.request);
Expand Down Expand Up @@ -431,6 +433,31 @@ describe('test http parser', () => {
assert.equal(ctx.body, `Redirecting to ${url5}.`);
assert.equal(ctx.type, 'text/plain');
});

describe('test onerror', () => {
it('test throw error', () => {
const app = new Application();
assert.throws(
() => {
app.onerror('foo');
},
TypeError,
'non-error thrown: foo'
);
});
it('test emit error', () => {
const app = new Application();
const err = new Error('mock stack null');
err.stack = null;
app.onerror(err);
let msg = '';
mm(console, 'error', input => {
if (input) msg = input;
});
app.onerror(err);
assert(msg === ' Error: mock stack null');
});
});
});

function escape(html) {
Expand Down