cpeak 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +11 -0
  2. package/src/index.js +72 -0
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "cpeak",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Cododev Technology",
10
+ "license": "ISC"
11
+ }
package/src/index.js ADDED
@@ -0,0 +1,72 @@
1
+ const http = require("node:http");
2
+ const fs = require("node:fs/promises");
3
+
4
+ class CPeak {
5
+ constructor() {
6
+ this.server = http.createServer();
7
+ this.routes = {};
8
+ this.middleware = [];
9
+
10
+ this.server.on("request", (req, res) => {
11
+ // Send a file back to the client
12
+ res.sendFile = async (path, mime) => {
13
+ const fileHandle = await fs.open(path, "r");
14
+ const fileStream = fileHandle.createReadStream();
15
+
16
+ res.setHeader("Content-Type", mime);
17
+
18
+ fileStream.pipe(res);
19
+ };
20
+
21
+ // Set the status code of the response
22
+ res.status = (code) => {
23
+ res.statusCode = code;
24
+ return res;
25
+ };
26
+
27
+ // Send a json data back to the client (for small json data, less than the highWaterMark)
28
+ res.json = (data) => {
29
+ // This is only good for bodies that their size is less than the highWaterMark value
30
+ res.setHeader("Content-Type", "application/json");
31
+ res.end(JSON.stringify(data));
32
+ };
33
+
34
+ // Run all the middleware functions before we run the corresponding route
35
+ const runMiddleware = (req, res, middleware, index) => {
36
+ // Out exit point...
37
+ if (index === middleware.length) {
38
+ // If the routes object does not have a key of req.method + req.url, return 404
39
+ if (!this.routes[req.method.toLocaleLowerCase() + req.url]) {
40
+ return res
41
+ .status(404)
42
+ .json({ error: `Cannot ${req.method} ${req.url}` });
43
+ }
44
+
45
+ this.routes[req.method.toLowerCase() + req.url](req, res);
46
+ } else {
47
+ middleware[index](req, res, () => {
48
+ runMiddleware(req, res, middleware, index + 1);
49
+ });
50
+ }
51
+ };
52
+
53
+ runMiddleware(req, res, this.middleware, 0);
54
+ });
55
+ }
56
+
57
+ route(method, path, cb) {
58
+ this.routes[method + path] = cb;
59
+ }
60
+
61
+ beforeEach(cb) {
62
+ this.middleware.push(cb);
63
+ }
64
+
65
+ listen(port, cb) {
66
+ this.server.listen(port, () => {
67
+ cb();
68
+ });
69
+ }
70
+ }
71
+
72
+ module.exports = CPeak;