Skip to content

Commit

Permalink
feat: set version 1.1.5
Browse files Browse the repository at this point in the history
feat: added cache option and onBefore, onAfter
feat: create redirect types (header, meta, js)
  • Loading branch information
sanchezzzhak committed Aug 6, 2024
1 parent 1013554 commit 0f1b75a
Show file tree
Hide file tree
Showing 7 changed files with 139 additions and 69 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-moleculer-web",
"version": "1.1.4",
"version": "1.1.5",
"description": "Fast web app service for moleculer.js + uWebSockets.js",
"main": "src/index.js",
"repository": {
Expand All @@ -12,7 +12,7 @@
},
"homepage": "https://github.com/sanchezzzhak/node-moleculer-web#readme",
"dependencies": {
"ejs": "^3.1.9",
"ejs": "^3.1.10",
"moleculer": "^0.14.32",
"qs": "^6.12.1",
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.44.0"
Expand Down
115 changes: 69 additions & 46 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class AppService extends Service {
module.exports = AppService
```
### Format bind route
### Router path
* `<request type> / #c:<controller name>.<action>`
* `<request type> / #s:<service name>.<action>`
* allowed request types:
Expand All @@ -90,102 +90,125 @@ module.exports = AppService
* `put` - HTTP PUT
* `trace` - HTTP TRACE
### Router Options
* `cache` - second http cache
* `onBefore(route, req, res)` - Function before call for controller or service
* `onAfter(route, req, res)` - Function after call for controller or service
Example options for createRoute
```js
this.createRoute('get / #c:home.index', {cache: 5});
this.bindRoutes();
```
### Controller API
* properties:
* requestData - read request data / write headers
* cookieData - read/write cookie
| **property** | **description** |
|:----------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------|
| `requestData` | read request data |
| `cookieData` | read/write cookie |
| `requestData or cookieData` (The property objects are available after executing the `this.initRequest()` method inside the controller method) |
| `redirectType` | "header" \| "meta" \| "js" (default meta) |
| `format` | default response content type default `html` |
| `statusCode` | default response http code number `200` |
| `statusCodeText` | default response http code string `200 OK` |
### Example Controllers
response json object
```js
class Home extends AbstractController {
index() {
return this.asJson({}, 200);
}
async index() {
return this.asJson({}, 200);
}
}
```
response redirect to other url
```js
class Home extends AbstractController {
index() {
return this.redirect('https://youdomain.dev', 301);
}
async index() {
return this.redirect('https://youdomain.dev', 301);
}
}
```
response ejs template
```js
class Home extends AbstractController {
index() {
return this.render({
async index() {
return this.render({
template, params, httpCode: 200, format: 'html'
});
}
}
}
```
response raw
```js
class Home extends AbstractController {
index() {
return this.renderRaw({view: 'string', httpCode: 200, format: 'html'});
}
async index() {
return this.renderRaw({view: 'string', httpCode: 200, format: 'html'});
}
}
```
or
```js
class Home extends AbstractController {
index() {
return 'Hello World'
}
async index() {
return 'Hello World'
}
}
```
Read or Write Cookie
```js
class Home extends AbstractController {
async index() {
this.initRequest();
// read
const cookievalue= this.cookieData.get('my_cookievalue', 1*new Date);
// write
async index() {
this.initRequest();
// read
const cookievalue= this.cookieData.get('my_cookievalue', 1*new Date);
// write
this.cookieData.set('my_cookievalue', cookievalue)

return cookievalue;
}
return cookievalue;
}
}
```
get request data
```js
class Home extends AbstractController {
async index() {
this.initRequest();
const headers = this.requestData.headers;
const ip = this.requestData.ip;
const query = this.requestData.query ?? {};
const referer = this.requestData.referer;
const currentUrl = this.requestData.url;
const userAgent = this.requestData.userAgent;
return this.asJson({headers, ip, query, referer, currentUrl, userAgent}, 200);
async index() {
this.initRequest();
const headers = this.requestData.headers;
const ip = this.requestData.ip;
const query = this.requestData.query ?? {};
const referer = this.requestData.referer;
const currentUrl = this.requestData.url;
const userAgent = this.requestData.userAgent;

return this.asJson({headers, ip, query, referer, currentUrl, userAgent}, 200);
}
}
```
call another microservice service in controller
```js
class Home extends AbstractController {
async index() {
const data = await this.broker.call('service-name.action', {
email: 'test'
}) ?? {};
return this.asJson(data, 200);
}
async index() {
const data = await this.broker.call('service-name.action', {
email: 'test'
}) ?? {};
return this.asJson(data, 200);
}
}
```
read post body
```js
class Home extends AbstractController {
async index() {
const body = await this.readBody();
return this.asJson({body}, 200);
}
async index() {
const body = await this.readBody();
return this.asJson({body}, 200);
}
}
```
Expand Down
26 changes: 23 additions & 3 deletions src/abstract-controller.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const ejs = require('ejs');
const {getMime} = require('./utils/mime');
const REDIRECT_TYPES = require("./redirect-types");
const HTTP_CODES = require('./utils/http-codes');
const Timer = require("./utils/timer");
const RequestData = require("./request-data");
const CookieData = require("./cookie-data");


/** @typedef {import("uWebSockets.js").HttpRequest} HttpRequest */
/** @typedef {import("uWebSockets.js").HttpResponse} HttpResponse */

Expand Down Expand Up @@ -41,6 +43,7 @@ const readBody = (res, cb, err) => {
};

class AbstractController {

/** @type {RequestData|null} */
requestData = null;
/** @type {CookieData|null} */
Expand All @@ -56,8 +59,11 @@ class AbstractController {
/** @type {ServiceBroker} broker */
broker;

/** */
clientHints = false;

redirectType = REDIRECT_TYPES.REDIRECT_TYPE_META;

constructor(opts = {}) {
this.broker = opts.broker;
this.req = opts.req;
Expand Down Expand Up @@ -193,10 +199,24 @@ class AbstractController {
* @param {number} httpCode
*/
redirect(location, httpCode = 301) {
this.writeHeader('location', location);
this.setStatus(httpCode);
const encodedLoc = location.replace(/"/g, "%22");
return `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`;

if (this.redirectType === REDIRECT_TYPES.REDIRECT_TYPE_META) {
this.setStatus(httpCode);
this.writeHeader('location', location);
return `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`;
}

if (this.redirectType === REDIRECT_TYPES.REDIRECT_TYPE_JS) {
return `<!DOCTYPE html><html><head><script>window.location.href='${location}'</script></head></html>`;
}

if (this.redirectType === REDIRECT_TYPES.REDIRECT_TYPE_HEADER) {
this.setStatus(httpCode);
this.writeHeader('location', location);
}

return '';
}

}
Expand Down
17 changes: 14 additions & 3 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,22 @@ export type JSONArray = Array<JSONValue>;
type RouteOptionMethod = "get" | "post" | "any" | "options"
| "head" | "put" | "connect" | "trace" | "patch" | "del";

type PortSchemaOption = "node" | "auto";

export interface RouteOptions {
path: string;
method: RouteOptionMethod;
controller?: string;
action?: string;
service?: string;
cache?: number;
onBefore?: Function;
onAfter?: Function;
}
export interface CreateRouteOption {
cache?: number;
onBefore?: Function;
onAfter?: Function;
}

export interface UwsServerSettings {
Expand All @@ -34,7 +44,7 @@ export interface UwsServerSettings {
ip: string;
publicDir: null | string;
publicIndex: boolean | string;
portSchema: null | string;
portSchema: null | PortSchemaOption;
routes: Array<RouteOptions>;
controllers: {
[name: string]: typeof AbstractController;
Expand All @@ -45,7 +55,6 @@ export interface RenderRawOptions {
view: string;
httpCode?: string | null
format?: string | null;

}

export interface RenderOptions {
Expand Down Expand Up @@ -109,6 +118,7 @@ export class AbstractController {
format: string;
statusCode: number;
statusCodeText: string;
redirectType: string;
headers: {
[name: string]: any;
}
Expand Down Expand Up @@ -153,7 +163,8 @@ export interface UwsServer {
started(): Promise<void>;

methods: {
createRoute(route: RouteOptions | string): void;
createRoute(route: string, options: CreateRouteOption): void;
addRoute(route: RouteOptions): void;
bindRoutes(): void;
bindRoutesStatic(): void;
getServerUws(): TemplatedApp | null;
Expand Down
5 changes: 5 additions & 0 deletions src/redirect-types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
REDIRECT_TYPE_META: 'meta',
REDIRECT_TYPE_JS: 'js',
REDIRECT_TYPE_HEADER: 'header',
}
2 changes: 1 addition & 1 deletion src/utils/uws-send-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async function uwsSendFile(res, req, options = {}) {
if (end < 0) end = 0;
let readStream = createReadStream(path, {start, end});
let compressed = false;
options.compress - false;
options.compress = false;
if (options.compress) {
const l = options.compressionOptions.priority.length;
for (let i = 0; i < l; i++) {
Expand Down
Loading

0 comments on commit 0f1b75a

Please sign in to comment.