Browse Source

Update 0.0.10

master
186526 1 month ago
parent
commit
941ded7435
Signed by: 186526 GPG Key ID: C7EB1E6B8CC5E51D
12 changed files with 207 additions and 80 deletions
  1. 39
      Plugins/register.js
  2. 84
      index.d.ts
  3. 6
      index.js
  4. 2
      package.json
  5. 5
      src/node/node.js
  6. 29
      src/rep.js
  7. 17
      src/sw/sw.js
  8. 9
      test/index.cjs
  9. 13
      test/index.js
  10. 16
      test/index.test.js
  11. 51
      test/sw/index.html
  12. 16
      test/webpack.config.cjs

39
Plugins/register.js

@ -0,0 +1,39 @@
const getReallyPrefix = (relativePrefix, globalPrefix) => {
const prefix = new URL("http://sw2express.localhost");
prefix.pathname = globalPrefix;
const reallyPrefix = new URL(relativePrefix, prefix.href);
return reallyPrefix.pathname;
};
export default {
name: "register",
func: (that) => (func, globalPrefix = "/") => {
const app = {
route: (prefix) => {
const reallyRoute = that.route(getReallyPrefix(prefix, globalPrefix));
return reallyRoute;
},
use: (Handler) => {
that._registerMiddlewares.push({
prefix: globalPrefix,
Handler: Handler,
});
},
};
func(app);
return that;
},
bootstrap: (app) => {
app._register = true;
app._registerMiddlewares = [];
app.use(async (req, rep) => {
app._registerMiddlewares.forEach(async (handler) => {
if (req.path.indexOf(handler.prefix) === 0) {
await handler.Handler(req, rep);
}
});
});
},
};

84
index.d.ts

@ -18,16 +18,31 @@ declare namespace sw2express {
/**
* Handle Get Request on this route
* @param func Handler
```
routeOnRoot.GET(async(req, rep) => "Hello World");
routeOnRoot.GET(async(req, rep) => new Object({Hello:"World"}));
routeOnRoot.GET(async(req, rep) => {rep.end("Hello World");});
```
*/
GET(func: sw2express.Handler): this;
/**
* Handle Post Request on this route
* @param func Handler
```
routeOnRoot.POST(async(req, rep) => "Hello World");
routeOnRoot.POST(async(req, rep) => new Object({Hello:"World"}));
routeOnRoot.POST(async(req, rep) => {rep.end("Hello World");});
```
*/
POST(func: sw2express.Handler): this;
/**
* Handle ALL Request on this route (Low priority)
* @param func Handler
```
routeOnRoot.all(async(req, rep) => "Hello World");
routeOnRoot.all(async(req, rep) => new Object({Hello:"World"}));
routeOnRoot.all(async(req, rep) => {rep.end("Hello World");});
```
*/
all(func: sw2express.Handler): this;
}
@ -52,12 +67,38 @@ declare namespace sw2express {
*
* @param req Request Object
* @param rep Reply Object
* @return if Answer === String, it will be rep.end
* @return it will be rep.json ||rep.end
*/
type Handler = (
req: sw2express.Request,
rep: sw2express.Reply
) => Promise<string> | string | undefined;
) => Promise<string> | Promise<Object> | Promise<undefined>;
/**
*
* @param app Sw=>Express Application Router Interface.
*/
type Application = (app: sw2express.appRouteInterface) => any;
interface appRouteInterface {
/**
* Add a Middleware for this app
* @param MiddleWare Middlware
```
app.use(async(req,rep)={
rep.setHeader("hello","world");
});
```
*/
use(MiddleWare: sw2express.Handler): this;
/**
* Create a route
* @param prefix prefix
```
const routeOnRoot = app.route('/');
```
*/
route(prefix: string): sw2express.route;
}
interface Request {
/**
* Request path, like "/foo/bar"
@ -170,28 +211,67 @@ declare namespace sw2express {
declare class sw2express {
/**
* Create an Sw=>Express Application
```
const app = new sw2express();
```
*/
constructor(options?: sw2express.Options);
/**
* Add a Middleware for this app
* @param MiddleWare Middlware
```
app.use(async(req,rep)={
rep.setHeader("hello","world");
});
```
*/
use(MiddleWare: sw2express.Handler): this;
/**
* Create a route
* @param prefix prefix
```
const routeOnRoot = app.route('/');
```
*/
route(prefix: string): sw2express.route;
/**
* Extend app func.
* @param plugins plugins
```
app.extend({
name: "say",
func: (app) => (text) => console.log(text, app),
bootstrap: (app) => {
app._say = true;
},
});
app.say("Hello world");
```
*/
extend(plugins: sw2express.plugin): sw2express.plugin;
/**
* Make a Application listen on this port (if can)
*
```
app.listen(8080);
```
* @param port
*/
listen(port: number): any;
/**
* Register A Application
* need `this.extend(registerPlugin)` First.
*
```
import registerPlugin from 'sw2express/Plugins/register.js';
app.extend(registerPlugin);
app.register((app) => {
app.route("./bar").all(async (req, rep) => "Hello World");
}, "/foo/");
```
* @param app Application Router.
*/
register(app: sw2express.Application): this;
}
export default sw2express;
/**

6
index.js

@ -84,9 +84,9 @@ class sw2express {
}
}
}
async extend({ name, func, bootstrap }) {
this[name] = func;
return await bootstrap(this);
extend({ name, func, bootstrap }) {
this[name] = func(this);
return bootstrap(this);
}
}

2
package.json

@ -6,7 +6,7 @@
"import": "./index.js"
},
"name": "sw2express",
"version": "0.0.9-swfix",
"version": "0.0.10",
"description": "A lite & simple cross-platform Express-like web application framework",
"directories": {
"test": "test"

5
src/node/node.js

@ -16,7 +16,10 @@ async function doRequest(func, NodeRequest, NodeReply) {
await doRequest(page.Code(500).GenAsync, NodeRequest, NodeReply);
console.log(e.stack);
});
if (!NodeReply.isEnd) NodeReply.end(rep);
if (!NodeReply.isEnd) {
if (typeof rep !== "object") NodeReply.end(rep);
else NodeReply.json(rep);
}
}
export const newHTTPServer = async (port) => {
return async (that) => {

29
src/rep.js

@ -5,7 +5,7 @@ export class nodeReply {
this.request = request;
this.response = response;
this.statusCode = 200;
this.headers = headers;
this.headers = Object.assign({}, headers);
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
@ -51,17 +51,10 @@ export class nodeReply {
return true;
}
json(text) {
this.response.statusCode = this.statusCode;
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
}
for (let i in this.headers) {
if (i !== "Content-Type") {
this.response.setHeader(i, this.headers[i]);
}
if (this.getHeader("Content-Type") === "text/plain; charset=utf-8") {
this.setHeader("Content-Type", "application/json; charset=utf-8");
}
this.isSendHeader = true;
this.response.write(text);
this.end(JSON.stringify(text));
return this;
}
Nativeend(text) {
@ -70,6 +63,9 @@ export class nodeReply {
this.isEnd = true;
return true;
}
set(a, b) {
this[a] = b;
}
}
export class swReply {
@ -77,7 +73,7 @@ export class swReply {
//this.response = response;
this.request = request;
this.statusCode = 200;
this.headers = headers;
this.headers = Object.assign({}, headers);
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
@ -114,10 +110,10 @@ export class swReply {
return this;
}
json(text) {
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
if (this.getHeader("Content-Type") === "text/plain; charset=utf-8") {
this.setHeader("Content-Type", "application/json; charset=utf-8");
}
this.send(text);
this.end(JSON.stringify(text));
return this;
}
end(text) {
@ -126,4 +122,7 @@ export class swReply {
this.isEnd = true;
return this;
}
set(a, b) {
this[a] = b;
}
}

17
src/sw/sw.js

@ -27,10 +27,14 @@ export const makeHandler = (that) => {
} else {
answer = await doRequest(page.Code(404).GenAsync, req, rep);
}
}else{
answer = await doRequest(async(req,rep)=>{
"NotThingToDoHere."
}, req, rep);
} else {
answer = await doRequest(
async (req, rep) => {
"NotThingToDoHere.";
},
req,
rep
);
}
return answer;
};
@ -40,6 +44,9 @@ export async function doRequest(func, req, rep) {
await doRequest(page.Code(500).GenAsync, req, rep);
console.log(e.stack);
});
if (!rep.isEnd) rep.end(funcAnswer);
if (!rep.isEnd) {
if (typeof funcAnswer !== "object") rep.end(funcAnswer);
rep.json(funcAnswer);
}
return await rep.GenResponse();
}

9
test/index.cjs

@ -1,9 +0,0 @@
const sw2express = require('../build/index.cjs').default;
global.globalThis = global;
const app = new sw2express({
cluster: require('os').cpus().length,
});
app.route('/').GET(async(req,rep)=>{
rep.send("hello world");
})
app.listen(8080)

13
test/index.js

@ -3,15 +3,7 @@ import sw2express, { checkPlatform } from "../index.js";
const app = new sw2express({
logger: false,
ETag: false,
cluster: 8,
});
const Platform = checkPlatform();
app.use(async (req, rep) => {
rep.setHeader("Hello", "World");
if (Platform === "SW") {
rep.send("Send From Service Worker\n");
}
cluster: 10,
});
app
@ -27,5 +19,6 @@ app
);
app.route("/echo").GET(async (req, rep) => "Hello World");
app.route("/json").GET(async (req, rep) => new Object({ hello: "world" }));
app.listen(8080);
app.listen(8081);

16
test/index.test.js

@ -0,0 +1,16 @@
import sw2express from "../index.js";
import registerPlugin from "../Plugins/register.js";
const app = new sw2express();
app.extend(registerPlugin);
app.register((app) => {
app.route("./bar").all(async (req, rep) => "Hello World");
}, "/foo/");
app.extend({
name: "say",
func: (app) => (text) => console.log(text, app),
bootstrap: (app) => {
app._say = true;
},
});
app.say("Hello world");
app.listen(8082);

51
test/sw/index.html

@ -1,27 +1,26 @@
<script>
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js", {
scope: "/",
})
.then((registration) =>{
console.info(
`Service Worker registration successful with scope: ${registration.scope}`
)
window.location.href = "/";
}
)
.catch((error) =>
console.warn(`Service Worker registration failed: ${error}`)
);
}
});
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("controllerchange", () => {
window.location.reload();
});
}
});
</script>
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js", {
scope: "/",
})
.then((registration) => {
console.info(
`Service Worker registration successful with scope: ${registration.scope}`
);
window.location.href = "/";
})
.catch((error) =>
console.warn(`Service Worker registration failed: ${error}`)
);
}
});
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("controllerchange", () => {
window.location.reload();
});
}
});
</script>

16
test/webpack.config.cjs

@ -1,9 +1,9 @@
module.exports = {
mode: 'development',
target: 'node',
resolve: {
fallback: {
"cluster": false,
}
}
}
mode: "development",
target: "node",
resolve: {
fallback: {
cluster: false,
},
},
};
Loading…
Cancel
Save