Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@foal/core

Package Overview
Dependencies
Maintainers
1
Versions
98
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@foal/core - npm Package Compare versions

Comparing version 0.2.2 to 0.3.0

dist/src/controllers/factories/pre-hook.d.ts

9

dist/src/controllers/binders/controller.binder.d.ts
import 'reflect-metadata';
import { Injector } from '../../di/injector';
import { Type } from '../../interfaces';
import { ExpressContextDef, ExpressMiddleware, ModuleContextDef, ModuleHooks } from '../interfaces';
import { MethodBinding, MethodPrimitiveBinding } from '../interfaces';
export declare abstract class ControllerBinder<T> {
constructor();
bindController(path: string, ControllerClass: Type<T>): (injector: Injector, moduleHooks: ModuleHooks, moduleContextDef: ModuleContextDef) => {
expressRouter: any;
};
protected abstract expressRouter(path: string, controller: T, getExpressMiddlewares: (methodName: string, defaultContextDef?: ExpressContextDef) => ExpressMiddleware[]): any;
bindController(path: string, ControllerClass: Type<T>): (injector: Injector) => MethodBinding[];
protected abstract bind(controller: T): MethodPrimitiveBinding[];
private getPreMiddlewares(ControllerClass, methodName);
}

@@ -38,6 +38,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var get = require("lodash/get");
var set = require("lodash/set");
require("reflect-metadata");
var utils_1 = require("../utils");
var ControllerBinder = /** @class */ (function () {

@@ -48,75 +45,35 @@ function ControllerBinder() {

var _this = this;
return function (injector, moduleHooks, moduleContextDef) {
return function (injector) {
var controller = injector.get(ControllerClass);
if (!controller) {
throw new Error(ControllerClass.name + " is not injected");
throw new Error(ControllerClass.name + " should be declared in a module.");
}
function getExpressMiddlewares(methodName) {
var classHooks = Reflect.getMetadata("hooks:express", ControllerClass) || [];
var methodHooks = Reflect.getMetadata("hooks:express", ControllerClass.prototype, methodName) || [];
return moduleHooks.express.concat(classHooks).concat(methodHooks).map(function (hook) { return hook(injector); });
}
function getContextualMiddlewares(methodName) {
var classHooks = Reflect.getMetadata("hooks:contextual", ControllerClass) || [];
var methodHooks = Reflect.getMetadata("hooks:contextual", ControllerClass.prototype, methodName) || [];
return moduleHooks.contextual.concat(classHooks).concat(methodHooks).map(function (hook) { return hook(injector); });
}
function getExpressContextDef(methodName) {
var classContextDef = Reflect.getMetadata("contextDef:express", ControllerClass) || [];
var methodContextDef = Reflect.getMetadata("contextDef:express", ControllerClass.prototype, methodName) || [];
return moduleContextDef.express.concat(classContextDef).concat(methodContextDef);
}
function getExpressContextMaker(methodName, defaultContextDef) {
if (defaultContextDef === void 0) { defaultContextDef = []; }
var contextDef = getExpressContextDef(methodName);
return utils_1.catchErrors(function (req, res, next) {
set(req, 'foal.context', {});
for (var _i = 0, _a = defaultContextDef.concat(contextDef); _i < _a.length; _i++) {
var tuple = _a[_i];
set(req.foal.context, tuple.ctx, get(req, tuple.req));
return _this.bind(controller).map(function (binding) {
var preMiddlewares = _this.getPreMiddlewares(ControllerClass, binding.controllerMethodName)
.map(function (pM) { return (function (ctx) { return pM(ctx, injector); }); });
var methodMiddleware = function (ctx) { return __awaiter(_this, void 0, void 0, function () { var _a; return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = ctx;
return [4 /*yield*/, binding.controllerMethodBinder(ctx)];
case 1: return [2 /*return*/, _a.result = _b.sent()];
}
next();
});
}
function getExpressContextualMiddleware(methodName) {
var _this = this;
var contextualMiddlewares = getContextualMiddlewares(methodName);
return utils_1.catchErrors(function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
var _i, contextualMiddlewares_1, middleware, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_i = 0, contextualMiddlewares_1 = contextualMiddlewares;
_b.label = 1;
case 1:
if (!(_i < contextualMiddlewares_1.length)) return [3 /*break*/, 4];
middleware = contextualMiddlewares_1[_i];
_a = req.foal;
return [4 /*yield*/, middleware(req.foal.context)];
case 2:
_a.context = _b.sent();
_b.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
next();
return [2 /*return*/];
}
});
}); });
}
function getGeneratedExpressMiddlewares(methodName, defaultContextDef) {
return getExpressMiddlewares(methodName).concat([
getExpressContextMaker(methodName, defaultContextDef),
getExpressContextualMiddleware(methodName)
]);
}
return {
expressRouter: _this.expressRouter(path, controller, getGeneratedExpressMiddlewares)
};
}); }); };
var middlewares = preMiddlewares.concat([methodMiddleware]);
return {
httpMethod: binding.httpMethod,
middlewares: middlewares,
paths: [path, binding.path],
successStatus: binding.successStatus
};
});
};
};
ControllerBinder.prototype.getPreMiddlewares = function (ControllerClass, methodName) {
var classPreMiddlewares = Reflect.getMetadata('pre-middlewares', ControllerClass) || [];
var methodPreMiddlewares = Reflect.getMetadata('pre-middlewares', ControllerClass.prototype, methodName) || [];
return classPreMiddlewares.concat(methodPreMiddlewares);
};
return ControllerBinder;
}());
exports.ControllerBinder = ControllerBinder;
export { ControllerBinder } from './controller.binder';
export * from './basic';
export * from './rest';

@@ -8,3 +8,2 @@ "use strict";

exports.ControllerBinder = controller_binder_1.ControllerBinder;
__export(require("./basic"));
__export(require("./rest"));

@@ -1,7 +0,7 @@

import { ExpressContextDef, ExpressMiddleware } from '../../interfaces';
import { MethodPrimitiveBinding } from '../../interfaces';
import { ControllerBinder } from '../controller.binder';
import { RestController } from './rest-controller.interface';
export declare class RestBinder extends ControllerBinder<RestController> {
protected expressRouter(path: string, controller: RestController, getExpressMiddlewares: (methodName: string, defaultContextDef?: ExpressContextDef) => ExpressMiddleware[]): any;
protected bind(controller: RestController): MethodPrimitiveBinding[];
}
export declare const rest: RestBinder;

@@ -13,5 +13,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var express = require("express");
var errors_1 = require("../../errors");
var controller_binder_1 = require("../controller.binder");
var handlers_1 = require("./handlers");
var RestBinder = /** @class */ (function (_super) {

@@ -22,19 +21,77 @@ __extends(RestBinder, _super);

}
RestBinder.prototype.expressRouter = function (path, controller, getExpressMiddlewares) {
var router = express.Router();
// Are we good with myPath////toto?
var defaultcontextDef = [
{ req: 'body', ctx: 'data' },
{ req: 'params.id', ctx: 'id' },
{ req: 'query', ctx: 'params.query' }
RestBinder.prototype.bind = function (controller) {
return [
{
controllerMethodBinder: function (ctx) {
if (!controller.getAll) {
throw new errors_1.NotImplementedError();
}
return controller.getAll(ctx.params);
},
controllerMethodName: 'getAll',
httpMethod: 'GET',
path: '/',
successStatus: 200,
},
{
controllerMethodBinder: function (ctx) {
if (!controller.create) {
throw new errors_1.NotImplementedError();
}
return controller.create(ctx.data, ctx.params);
},
controllerMethodName: 'create',
httpMethod: 'POST',
path: '/',
successStatus: 201,
},
{
controllerMethodBinder: function (ctx) {
if (!controller.delete) {
throw new errors_1.NotImplementedError();
}
return controller.delete(ctx.id, ctx.params);
},
controllerMethodName: 'delete',
httpMethod: 'DELETE',
path: '/:id',
successStatus: 200,
},
{
controllerMethodBinder: function (ctx) {
if (!controller.get) {
throw new errors_1.NotImplementedError();
}
return controller.get(ctx.id, ctx.params);
},
controllerMethodName: 'get',
httpMethod: 'GET',
path: '/:id',
successStatus: 200,
},
{
controllerMethodBinder: function (ctx) {
if (!controller.patch) {
throw new errors_1.NotImplementedError();
}
return controller.patch(ctx.id, ctx.data, ctx.params);
},
controllerMethodName: 'patch',
httpMethod: 'PATCH',
path: '/:id',
successStatus: 200,
},
{
controllerMethodBinder: function (ctx) {
if (!controller.update) {
throw new errors_1.NotImplementedError();
}
return controller.update(ctx.id, ctx.data, ctx.params);
},
controllerMethodName: 'update',
httpMethod: 'PUT',
path: '/:id',
successStatus: 200,
},
];
router.route(path)
.get(getExpressMiddlewares('getAll', defaultcontextDef), handlers_1.getGetAllHandler(controller))
.post(getExpressMiddlewares('create', defaultcontextDef), handlers_1.getPostHandler(controller));
router.route(path + "/:id")
.delete(getExpressMiddlewares('delete', defaultcontextDef), handlers_1.getDeleteHandler(controller))
.get(getExpressMiddlewares('get', defaultcontextDef), handlers_1.getGetHandler(controller))
.patch(getExpressMiddlewares('patch', defaultcontextDef), handlers_1.getPatchHandler(controller))
.put(getExpressMiddlewares('update', defaultcontextDef), handlers_1.getPutHandler(controller));
return router;
};

@@ -41,0 +98,0 @@ return RestBinder;

@@ -1,6 +0,1 @@

import { Injector } from '../../di/injector';
import { Context, Decorator, ExpressContextDef, ExpressMiddleware } from '../interfaces';
export declare function newExpressDecoratorWithInjector(hook: (injector: Injector) => ExpressMiddleware, contextDef?: ExpressContextDef): Decorator;
export declare function newExpressDecorator(middleware: ExpressMiddleware, contextDef?: ExpressContextDef): Decorator;
export declare function newContextualDecoratorWithInjector(hook: (injector: Injector) => ((ctx: Context) => Promise<Context>)): Decorator;
export declare function newContextualDecorator(middleware: (ctx: Context) => Promise<Context>): Decorator;
export { preHook } from './pre-hook';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var new_controller_decorator_with_injector_1 = require("./new-controller-decorator-with-injector");
function newExpressDecoratorWithInjector(hook, contextDef) {
return new_controller_decorator_with_injector_1.newControllerDecoratorWithInjector('express', hook, contextDef);
}
exports.newExpressDecoratorWithInjector = newExpressDecoratorWithInjector;
function newExpressDecorator(middleware, contextDef) {
return newExpressDecoratorWithInjector(function (injector) { return middleware; }, contextDef);
}
exports.newExpressDecorator = newExpressDecorator;
function newContextualDecoratorWithInjector(hook) {
return new_controller_decorator_with_injector_1.newControllerDecoratorWithInjector('contextual', hook);
}
exports.newContextualDecoratorWithInjector = newContextualDecoratorWithInjector;
function newContextualDecorator(middleware) {
return new_controller_decorator_with_injector_1.newControllerDecoratorWithInjector('contextual', function (injector) { return middleware; });
}
exports.newContextualDecorator = newContextualDecorator;
var pre_hook_1 = require("./pre-hook");
exports.preHook = pre_hook_1.preHook;
export * from './binders';
export * from './decorators';
export * from './pre-hooks';
export * from './factories';
export * from './errors';
export * from './utils';
export * from './interfaces';

@@ -7,5 +7,4 @@ "use strict";

__export(require("./binders"));
__export(require("./decorators"));
__export(require("./pre-hooks"));
__export(require("./factories"));
__export(require("./errors"));
__export(require("./utils"));

@@ -5,19 +5,18 @@ import { Injector } from '../di/injector';

}
export declare type ContextualMiddleware = (ctx: Context) => Promise<Context>;
export declare type NextFunction = (err?: Error) => void;
export declare type ExpressMiddleware = (req: any, res: any, next: NextFunction) => any;
export declare type ContextualHook = (injector: Injector) => ContextualMiddleware;
export declare type ExpressHook = (injector: Injector) => ExpressMiddleware;
export interface ModuleHooks {
express: ExpressHook[];
contextual: ContextualHook[];
export declare type Middleware = (ctx: Context) => Promise<any> | any;
export declare type PreMiddleware = (ctx: Context, injector: Injector) => Promise<any> | any;
export declare type Decorator = (target: any, methodName?: string) => void;
export declare type HttpMethod = 'POST' | 'GET' | 'PUT' | 'PATCH' | 'DELETE';
export interface MethodBinding {
httpMethod: HttpMethod;
paths: string[];
middlewares: Middleware[];
successStatus: number;
}
export declare type ExpressContextDef = {
req: string;
ctx: string;
}[];
export interface ModuleContextDef {
express: ExpressContextDef;
export interface MethodPrimitiveBinding {
controllerMethodBinder: (context: Context) => Promise<any>;
controllerMethodName: string;
httpMethod: HttpMethod;
path: string;
successStatus: number;
}
export declare type Decorator = (target: any, methodName?: string) => void;
export declare type Family = 'express' | 'contextual';
import 'reflect-metadata';
import { Decorator, ModuleContextDef, ModuleHooks } from './controllers/interfaces';
import { Decorator, MethodBinding } from './controllers/interfaces';
import { Injector } from './di/injector';

@@ -7,6 +7,4 @@ import { Type } from './interfaces';

services: Type<any>[];
controllerBindings?: ((injector: Injector, controllerHooks: ModuleHooks, controllerContextDef: ModuleContextDef) => {
expressRouter: any;
})[];
sharedControllerDecorators?: Decorator[];
controllerBindings?: ((injector: Injector) => MethodBinding[])[];
preHooks?: Decorator[];
imports?: {

@@ -19,5 +17,5 @@ module: FoalModule;

readonly injector: Injector;
private readonly router;
readonly methodsBindings: MethodBinding[];
constructor(foalModule: FoalModule, parentModule?: Foal);
expressRouter(): any;
private getPreMiddlewares(preHooks);
}
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var express = require("express");
require("reflect-metadata");

@@ -9,6 +16,6 @@ var injector_1 = require("./di/injector");

var _this = this;
this.router = express.Router();
foalModule.controllerBindings = foalModule.controllerBindings || [];
foalModule.imports = foalModule.imports || [];
foalModule.sharedControllerDecorators = foalModule.sharedControllerDecorators || [];
this.methodsBindings = [];
var controllerBindings = foalModule.controllerBindings || [];
var imports = foalModule.imports || [];
var modulePreHooks = foalModule.preHooks || [];
if (parentModule) {

@@ -21,2 +28,21 @@ this.injector = new injector_1.Injector(parentModule.injector);

foalModule.services.forEach(function (service) { return _this.injector.inject(service); });
var modulePreMiddlewares = this.getPreMiddlewares(modulePreHooks);
for (var _i = 0, controllerBindings_1 = controllerBindings; _i < controllerBindings_1.length; _i++) {
var controllerBinding = controllerBindings_1[_i];
for (var _a = 0, _b = controllerBinding(this.injector); _a < _b.length; _a++) {
var methodBinding = _b[_a];
this.methodsBindings.push(__assign({}, methodBinding, { middlewares: modulePreMiddlewares.map(function (e) { return (function (ctx) { return e(ctx, _this.injector); }); }).concat(methodBinding.middlewares) }));
}
}
for (var _c = 0, imports_1 = imports; _c < imports_1.length; _c++) {
var imp = imports_1[_c];
var importedModule = new Foal(imp.module, this);
var path = imp.path || '';
for (var _d = 0, _e = importedModule.methodsBindings; _d < _e.length; _d++) {
var methodBinding = _e[_d];
this.methodsBindings.push(__assign({}, methodBinding, { middlewares: modulePreMiddlewares.map(function (e) { return (function (ctx) { return e(ctx, _this.injector); }); }).concat(methodBinding.middlewares), paths: [path].concat(methodBinding.paths) }));
}
}
}
Foal.prototype.getPreMiddlewares = function (preHooks) {
var FakeModule = /** @class */ (function () {

@@ -28,14 +54,4 @@ function FakeModule() {

// Reverse the array to apply decorators in the proper order.
foalModule.sharedControllerDecorators.reverse().forEach(function (decorator) { return decorator(FakeModule); });
var expressHooks = Reflect.getMetadata('hooks:express', FakeModule) || [];
var contextualHooks = Reflect.getMetadata('hooks:contextual', FakeModule) || [];
var expressContextDef = Reflect.getMetadata('contextDef:express', FakeModule) || [];
foalModule.controllerBindings.forEach(function (getRouters) {
var expressRouter = getRouters(_this.injector, { express: expressHooks, contextual: contextualHooks }, { express: expressContextDef }).expressRouter;
_this.router.use(expressRouter);
});
foalModule.imports.forEach(function (imp) { return _this.router.use(imp.path || '/', new Foal(imp.module, _this).router); });
}
Foal.prototype.expressRouter = function () {
return this.router;
preHooks.reverse().forEach(function (decorator) { return decorator(FakeModule); });
return Reflect.getMetadata('pre-middlewares', FakeModule) || [];
};

@@ -42,0 +58,0 @@ return Foal;

{
"name": "@foal/core",
"version": "0.2.2",
"version": "0.3.0",
"description": "Backend framework written in TypeScript",

@@ -8,4 +8,4 @@ "main": "./dist/index.js",

"scripts": {
"test": "mocha --require ts-node/register ./**/*.spec.ts",
"test-watch": "mocha -w --require ts-node/register ./**/*.spec.ts",
"test": "mocha --require ts-node/register \"./src/**/*.spec.ts\"",
"test-watch": "mocha --require ts-node/register --watch --watch-extensions ts \"./src/**/*.spec.ts\"",
"compile": "tsc",

@@ -35,7 +35,3 @@ "prepublish": "tsc"

],
"peerDependencies": {
"express": "4.x"
},
"dependencies": {
"lodash": "^4.17.4",
"reflect-metadata": "^0.1.10"

@@ -47,3 +43,2 @@ },

"chai": "^4.1.2",
"express": "^4.15.4",
"mocha": "^3.5.3",

@@ -50,0 +45,0 @@ "ts-node": "^3.3.0",

@@ -8,3 +8,3 @@ # FoalTS

```ts
npm install --save express body-parser @foal/core
npm install --save express body-parser @foal/core @foal/express
```

@@ -31,3 +31,4 @@

import * as express from 'express';
import { Foal, Service, newExpressDecorator, rest, RestController, RestParams } from '@foal/core';
import { getCallback } from '@foal/express';
import { Foal, Service, rest, RestController, RestParams } from '@foal/core';

@@ -45,12 +46,11 @@ @Service()

const app = express();
const foal = new Foal({
services: [ User ],
controllerBindings: [ rest.bindController('/users', User) ],
sharedControllerDecorators: [
newExpressDecorator(bodyParser.urlencoded({ extended: false })),
newExpressDecorator(bodyParser.json())
]
controllerBindings: [ rest.bindController('/users', User) ]
});
app.use(foal.expressRouter());
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(getCallback(foal));
app.listen(3000, () => console.log('Listening...'));

@@ -57,0 +57,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc