Socket
Socket
Sign inDemoInstall

@bayerjs/core

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bayerjs/core - npm Package Compare versions

Comparing version 0.0.2-alpha.0 to 0.2.0-alpha.0

lib/request.d.ts

88

lib/index.d.ts
/// <reference types="node" />
/**
* Server class definitions for the Bayer.JS project.
*
* TODO: Write getting started page
*
* Copyright 2018 Nathan "SolarLiner" Graule
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { IncomingMessage, ServerResponse } from "http";
import { IncomingMessage, Server, ServerResponse } from "http";
import { OperatorFunction } from "rxjs";
/**
* Server middleware type.
*/
export declare type ServerMiddleware = OperatorFunction<IServerRequest, IServerRequest>;
/**
* Encapsulated Request and Response objects. The extra object can contain
* anything, and is mostly there for middleware that manipulate data.
*/
export interface IServerRequest {
/**
* Incoming request. Copied from Node.js's HTTP server module.
*/
req: IncomingMessage;
/**
* Server response. Copied from Node.js's HTTP server module.
*/
res: ServerResponse;
/**
* Extra data that middleware can add to the request object.
*
* NOTE: Express middleware that add data to the request/response object are
* redirected here instead, through Proxying.
*/
extra: {
[x: string]: any;
};
import { Request } from "./request";
import { Response } from "./response";
declare type RequestFunction = (req: IncomingMessage, res: ServerResponse) => void;
export interface IBayerCallback<T extends {
[x: string]: any;
}> {
req: Request;
res: Response;
extra: T;
}
export interface InternalMiddleware {
middleware: ServerMiddleware;
priority: number;
export declare type ServerMiddleware<T = any, U = any> = OperatorFunction<IBayerCallback<T>, IBayerCallback<U>>;
export default class Bayer<T = any> {
private middlewares;
private obs;
private reqFunc;
constructor();
use<U = T>(middleware: ServerMiddleware<T, U>, priority?: number): void;
listen(port?: number): Promise<Server>;
callback(): RequestFunction;
private sortMiddlewares;
private convertServerParams;
private terminateRequest;
private log;
private handleRequestError;
}
export { BaseServer } from "./base";
export { HTTPServer, HTTPSServer } from "./http";
export declare class HttpError extends Error {
code: number;
reason?: string;
constructor(statusCode: number, statusMessage?: string);
}
export * from "./request";
export * from "./response";
//# sourceMappingURL=index.d.ts.map
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
// Export server classes
var base_1 = require("./base");
exports.BaseServer = base_1.BaseServer;
var http_1 = require("./http");
exports.HTTPServer = http_1.HTTPServer;
exports.HTTPSServer = http_1.HTTPSServer;
var chalk_1 = __importDefault(require("chalk"));
var http_1 = require("http");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var request_1 = require("./request");
var response_1 = require("./response");
var Bayer = /** @class */ (function () {
function Bayer() {
var _this = this;
this.middlewares = new Array();
this.obs = new rxjs_1.Observable(function (sub) {
_this.reqFunc = function (req, res) {
var callbackObj = _this.convertServerParams(req, res);
sub.next(callbackObj);
};
});
}
Bayer.prototype.use = function (middleware, priority) {
if (priority === void 0) { priority = 0; }
this.middlewares.push({ middleware: middleware, priority: priority });
};
Bayer.prototype.listen = function (port) {
if (port === void 0) { port = 80; }
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
// tslint:disable-next-line:variable-name
return [2 /*return*/, new Promise(function (resolve, _reject) {
var cb = _this.callback();
var server = http_1.createServer(cb);
server.listen(port, function () { return resolve(server); });
})];
});
});
};
Bayer.prototype.callback = function () {
var _this = this;
this.sortMiddlewares();
var start;
var obs = this.obs.pipe(operators_1.tap(function () {
start = Date.now();
}), operators_1.mergeMap(function (v) {
var middleware$ = _this.middlewares.reduce(function (req, m) { return req.pipe(m.middleware); }, rxjs_1.of(v));
return middleware$.pipe(operators_1.catchError(function (err) {
_this.handleRequestError(err, v);
return rxjs_1.of(v);
}));
}), operators_1.tap(function (params) { return _this.terminateRequest(params, start); }));
obs.subscribe();
return this.reqFunc;
};
Bayer.prototype.sortMiddlewares = function () {
if (this.middlewares.length > 1) {
this.middlewares.sort(function (a, b) { return b.priority - a.priority; });
}
};
Bayer.prototype.convertServerParams = function (request, response) {
var req = new request_1.Request(request);
var res = new response_1.Response(response);
return { req: req, res: res, extra: {} };
};
Bayer.prototype.terminateRequest = function (_a, start) {
var req = _a.req, res = _a.res;
if (!res.done) {
res.status(404).send("Cannot " + (req.route.method || "GET") + " " + req.route.path);
}
var ms = Date.now() - start;
this.log(req, res, ms);
};
Bayer.prototype.log = function (req, res, ms) {
var _a = req.route, method = _a.method, path = _a.path;
var handleRequestError = res.statusCode, statusMessage = res.statusMessage;
var blue = chalk_1.default.blue, green = chalk_1.default.green, greenBright = chalk_1.default.greenBright;
var chalkResult = handleRequestError === 200 ? green : chalk_1.default.red;
process.stdout.write(chalk_1.default.grey(new Date().toLocaleString()) + " " + blue("Request") + " " + green(method) + " " + greenBright(path) + " " + ms + " ms - " + chalkResult(handleRequestError + " " + statusMessage) + "\n");
};
Bayer.prototype.handleRequestError = function (err, _a) {
var res = _a.res;
if (typeof err === "number") {
res.status(err).end();
}
else if (err instanceof HttpError) {
var ress = res.status(err.code);
if (err.reason)
return ress.send(err.reason);
ress.end();
}
else {
var ress = res.status(500, "Internal server error");
if (err instanceof Error)
return ress.send(err.name + " : " + err.message);
ress.end();
}
};
return Bayer;
}());
exports.default = Bayer;
var HttpError = /** @class */ (function (_super) {
__extends(HttpError, _super);
function HttpError(statusCode, statusMessage) {
var _this = _super.call(this, statusCode + " " + statusMessage) || this;
_this.name = "HttpError";
_this.code = statusCode;
_this.reason = statusMessage;
Object.setPrototypeOf(_this, HttpError.prototype);
Error.captureStackTrace(_this, _this.constructor);
return _this;
}
return HttpError;
}(Error));
exports.HttpError = HttpError;
__export(require("./request"));
__export(require("./response"));
//# sourceMappingURL=index.js.map
{
"name": "@bayerjs/core",
"version": "0.0.2-alpha.0",
"version": "0.2.0-alpha.0",
"description": "Bayer.JS core server library",

@@ -37,5 +37,8 @@ "keywords": [

"dependencies": {
"busboy": "^0.2.14",
"chalk": "^2.4.1",
"rxjs": "^6.3.3"
},
"devDependencies": {
"@types/busboy": "^0.2.3",
"@types/node": "^10.12.10",

@@ -42,0 +45,0 @@ "lerna": "^3.4.3",

@@ -1,11 +0,40 @@

# `core`
# `@bayerjs/core`
> TODO: description
Core server abstract library. Start the server with `Bayer.listen` or get a callback function with `Bayer.callback`.
## Usage
### Initialize a server object
#### HTTP Server
```typescript
import Bayer from "@bayerjs/core";
const app = new Bayer();
app.listen(); // Will listen on port 80 and 404 every request made to it
```
const core = require('core');
// TODO: DEMONSTRATE API
### Add middleware
```typescript
import { tap } from "rxjs/operators";
app.use(tap(({ req, res, extra }) => {
res.status(200, "OK").send("Hello world!");
}));
```
To pass data to middlewares further down, write into the `extra` object:
```typescript
import { map } from "rxjs/operators";
// The number as second parameter is the priority. See the reference doc.
server.use(tap(({ req, extra }) => {
// Push custom headers into the extra object
Object.keys(req.headers).filter(v => v.startsWith("x-")).forEach(v => {
extra[v] = req.headers[v];
});
}), 1);
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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