Skip to content

Commit

Permalink
enabled compact mode
Browse files Browse the repository at this point in the history
  • Loading branch information
calidion committed Sep 30, 2023
1 parent 5a2ded2 commit 4a7de06
Show file tree
Hide file tree
Showing 22 changed files with 378 additions and 95 deletions.
55 changes: 48 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ class Helloworld {
public async all(req: any, res: any) {
res.end(this.message);
}

@compact("/")
public async compactAll(ctx: any) {
ctx.res.end(this.message);
}

@http("*", "*", true)
public async httpCompactAll(ctx: any) {
ctx.res.end(this.message);
}
}

const aex = new Aex();
Expand Down Expand Up @@ -256,6 +266,7 @@ The member methods are of `IAsyncMiddleware` type.

1. http method name(s)
2. url(s);
3. use Compact mode?

You can just pass url(s) if you use http `GET` method only or you can use `@get` .

Expand All @@ -265,11 +276,16 @@ Here is how your define your handlers.
import { http, get, post } from "@aex/core";

class User {

// Classic http parameters passing
@http("get", ["/profile", "/home"])
profile() {}
profile(req, res, scope) {}

@http(["get", "post"], "/user/login")
login() {}
// Compact Mode parameters passing
@http(["get", "post"], "/user/login", true)
login(ctx) {
const {req, res, scope} = ctx;
}

@http("post", "/user/logout")
logout() {}
Expand Down Expand Up @@ -751,7 +767,8 @@ Aex provides `@inject` decorator for middleware injection.
`@inject` decrator takes two parameters:
1. injector: the main injected middleware for data further processing or policy checking
2. fallback: optional fallback when the injector fails and returned `false`
2. fallback?: optional fallback when the injector fails and returned `false`
3. useCompactMode?: `true` to use compact mode.
```ts
class User {
Expand All @@ -773,6 +790,14 @@ class User {
}
};
})
@inject(async function compactMode(this:User, ctx) {
this.name = "Peter";
ctx.req.session = {
user: {
name: "ok"
}
};
}, , true)
@inject(async function(this:User, req, res, scope) => {
this.name = "Peter";
if (...) {
Expand Down Expand Up @@ -910,9 +935,11 @@ class User {
});
```
## Middlewares
## Middlewares/Handlers
Middlewares/Handlers are defined like this:
Middlewares are defined like this:
1. Classic one
```ts
export type IAsyncMiddleware = (
Expand All @@ -922,7 +949,21 @@ export type IAsyncMiddleware = (
) => Promise<boolean | undefined | null | void>;
```
They return promise. so they must be called with `await` or `.then()`.
2. Compacted Mode
```ts
export interface IACompactedAsyncMiddeleWare {
req: IRequest;
res: IResponse;
scope?: Scope;
}

export type ICompactedAsyncMiddleware = (
context: IACompactedAsyncMiddeleWare
) => Promise<boolean | undefined | null | void>;
```
They return promises, so they must be called with `await` or `.then()`.
### Global middlewares
Expand Down
7 changes: 7 additions & 0 deletions __tests__/compatiblity-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Aex } from "../src/index";
import { Router } from "../src/index";
import { toAsyncMiddleware } from "../src/index";
import { GetTextWithAex } from "../src/index";
import { copyByKey } from "../src/util/kv";

test("Should compatible with express middlewares", async () => {
const aex = new Aex();
Expand Down Expand Up @@ -35,3 +36,9 @@ test("Should compatible with express middlewares", async () => {

await GetTextWithAex(aex, "Hello Aex!", "");
});

test("Should test copyByKey", async () => {
let a = {};
let b = { function() {} };
copyByKey(b, a);
});
28 changes: 27 additions & 1 deletion __tests__/decorators/body-spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// import * as express from 'express';
// tslint:disable-next-line:no-duplicate-imports

import { Aex } from "../../src/index";
import { Aex, IACompactedAsyncMiddeleWare } from "../../src/index";
import { body } from "../../src/index";
import { http } from "../../src/index";

Expand All @@ -17,6 +17,21 @@ class Body {
return this._name;
}

@http("post", "/user/login1", true)
@body()
public allCompacted(context: IACompactedAsyncMiddeleWare) {
const { req, res, scope } = context;
// console.log(context);
expect(this.name === "Aex");
expect(req.body.username === "aaa");
expect(req.body.password === "sososo");
expect(scope).toBeTruthy();
expect(scope?.body).toBeTruthy();
expect((scope?.body as any).username === "aaa");
expect((scope?.body as any).password === "sososo");
res.end("Body All!");
}

@http("post", "/user/login")
@body()
public all(req: any, res: any, scope: any) {
Expand Down Expand Up @@ -61,6 +76,17 @@ test("Should decorate methods with array", async () => {
);
});

test("Should decorate methods with array", async () => {
await PostText(
port,
{ username: "aaa", password: "sososo" },
"Body All!",
"/user/login1",
"localhost",
"POST"
);
});

test("Should not push again a calss", async () => {
let catched = false;
try {
Expand Down
85 changes: 85 additions & 0 deletions __tests__/decorators/compacted-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// import * as express from 'express';
// tslint:disable-next-line:no-duplicate-imports

import {
Aex,
IACompactedAsyncMiddeleWare,
// IAsyncMiddleware,
} from "../../src/index";
import { body } from "../../src/index";
import { http, compact } from "../../src/index";

import { PostText, initRandomPort } from "../../src/index";

class Body {
private _name: string;
constructor(name: string) {
this._name = name;
}

get name() {
return this._name;
}

@compact("post", "/user/login")
@body()
public all(context: IACompactedAsyncMiddeleWare) {
const { req, res, scope } = context;
// console.log(context);
expect(this.name === "Aex");
expect(req.body.username === "aaa");
expect(req.body.password === "sososo");
expect(scope).toBeTruthy();
expect(scope?.body).toBeTruthy();
expect((scope?.body as any).username === "aaa");
expect((scope?.body as any).password === "sososo");
res.end("Body All!");
}

@http("post", "/user/ok")
@body("roodod")
public road(_req: any, res: any) {
expect(this.name === "Aex");
res.end("Body Road!");
}
}

const aex = new Aex();

aex.push(Body, "Aex");
aex.prepare();

let port: number = 0;

beforeAll(async () => {
port = await initRandomPort(aex);
const user = aex.instances[0];
expect(user).toBeTruthy();
expect(user.name === "Aex").toBeTruthy();
});

test("Should work with context", async () => {
await PostText(
port,
{ username: "aaa", password: "sososo" },
"Body All!",
"/user/login",
"localhost",
"POST"
);
});

// test("Should not push again a calss", async () => {
// let catched = false;
// try {
// aex.push(Body);
// } catch (e) {
// catched = true;
// expect(e.message).toBe("Duplicated class found!");
// }
// expect(catched).toBeTruthy();
// });

afterAll(async () => {
aex.server?.close();
});
57 changes: 56 additions & 1 deletion __tests__/decorators/formdata-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { createReadStream, readFileSync } from "fs";
import { resolve } from "path";
import { Aex, formdata } from "../../src/index";
import { Aex, IACompactedAsyncMiddeleWare, formdata } from "../../src/index";
import { http } from "../../src/index";
import * as request from "request";

Expand Down Expand Up @@ -32,6 +32,27 @@ class Formdata {

copyByKey({ 1: {} }, {});
}

@http("post", "/file/upload1", true)
@formdata()
public async upload1(context: IACompactedAsyncMiddeleWare) {
const { res, scope } = context;
const { files, body } = scope as any;
expect(body["node"] === "v4").toBeTruthy();
expect(body["nods"] === "v5").toBeTruthy();
expect(files["file"].length === 3).toBeTruthy();
expect(files["oddd"].length === 1).toBeTruthy();
expect(this.name === "formdata");
const aaa = files["file"][0];
expect(String(readFileSync(aaa.temp)) === "AAA").toBeTruthy();
const bbb = files["file"][1];
expect(String(readFileSync(bbb.temp)) === "BBB").toBeTruthy();
const ccc = files["file"][2];
expect(String(readFileSync(ccc.temp)) === "CCC").toBeTruthy();
res.end("File Uploaded!");

copyByKey({ 1: {} }, {});
}
}

const aex = new Aex();
Expand Down Expand Up @@ -79,6 +100,40 @@ describe("formdata", () => {
expect(body === "File Uploaded!").toBeTruthy();
});

test("Should upload1 files", async () => {
const url = "http://localhost:" + port + "/file/upload1";

var formData = {
file: [
createReadStream(resolve(__dirname, "./fixtures/aaa.txt")),
createReadStream(resolve(__dirname, "./fixtures/bbb.txt")),
createReadStream(resolve(__dirname, "./fixtures/ccc.txt")),
],
oddd: createReadStream(resolve(__dirname, "./fixtures/ccc.txt")),
node: "v4",
nods: "v5",
};

var uploadOptions = {
url,
method: "POST",
formData: formData,
};

// let httpReq: any;

const body = await new Promise((resolve, reject) => {
request.post(uploadOptions, function (err: any, _resp: any, body: any) {
if (err) {
return reject(err);
} else {
resolve(body);
}
});
});
expect(body === "File Uploaded!").toBeTruthy();
});

afterAll(async () => {
aex.server?.close();
});
Expand Down
7 changes: 3 additions & 4 deletions __tests__/decorators/http-all-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@ class HttpAll {
public static message = "HttpAll Aex!";
@http("*", "*")
public async all(req: any, res: any, scope: any) {
const self = this as any;
expect(self.req).toBe(req);
expect(self.res).toBe(res);
expect(self.scope).toBe(scope);
expect(req).toBeTruthy();
expect(res).toBeTruthy();
expect(scope).toBeTruthy();
res.end(HttpAll.message);
}
}
Expand Down
Loading

0 comments on commit 4a7de06

Please sign in to comment.