cpeak 1.4.0 → 2.2.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.
package/README.md ADDED
@@ -0,0 +1,347 @@
1
+ # Cpeak
2
+
3
+ Cpeak is a minimal and fast Node.js framework inspired by Express.js.
4
+
5
+ This project is designed to be improved until it's ready for use in complex production applications, aiming to be more performant and minimal than Express.js. This framework is intended for HTTP applications that primarily deal with JSON and file-based message bodies.
6
+
7
+ This is an educational project that was started as part of the [Understanding Node.js: Core Concepts](https://www.udemy.com/course/understanding-nodejs-core-concepts/?referralCode=0BC21AC4DD6958AE6A95) course. If you want to learn how to build a framework like this, and get to a point where you can build things like this yourself, check out this course!
8
+
9
+ ## Why Cpeak?
10
+
11
+ - **Minimalism**: No unnecessary bloat, with zero dependencies. Just the core essentials you need to build fast and reliable applications.
12
+ - **Performance**: Engineered to be fast, **Cpeak** won’t sacrifice speed for excessive customizability.
13
+ - **Educational**: Every new change made in the project will be explained in great detail in a YouTube playlist (playlist will be added soon). Follow this project and let's see what it takes to build an industry-leading product!
14
+ - **Express.js Compatible**: You can easily refactor from Cpeak to Express.js and vice versa. Many npm packages that work with Express.js will also work with Cpeak.
15
+
16
+ ## Table of Contents
17
+
18
+ - [Getting Started](#getting-started)
19
+ - [Hello World App](#hello-world-app)
20
+ - [Documentation](#documentation)
21
+ - [Including](#including)
22
+ - [Initializing](#initializing)
23
+ - [Middleware](#middleware)
24
+ - [Route Handling](#route-handling)
25
+ - [URL Variables & Parameters](#url-variables--parameters)
26
+ - [Sending Files](#sending-files)
27
+ - [Error Handling](#error-handling)
28
+ - [Listening](#listening)
29
+ - [Util Functions](#util-functions)
30
+ - [serveStatic](#servestatic)
31
+ - [parseJSON](#parsejson)
32
+ - [Complete Example](#complete-example)
33
+ - [Versioning Notice](#versioning-notice)
34
+
35
+ ## Getting Started
36
+
37
+ Ready to dive in? Install **Cpeak** via npm:
38
+
39
+ ```bash
40
+ npm install cpeak
41
+ ```
42
+
43
+ ### Hello World App:
44
+
45
+ ```javascript
46
+ import cpeak from "cpeak";
47
+
48
+ const server = new cpeak();
49
+
50
+ server.route("get", "/", (req, res) => {
51
+ res.json({ message: "Hi there!" });
52
+ });
53
+
54
+ server.listen(3000, () => {
55
+ console.log("Server has started on port 3000");
56
+ });
57
+ ```
58
+
59
+ ## Documentation
60
+
61
+ ### Including
62
+
63
+ Include the framework like this:
64
+
65
+ ```javascript
66
+ import cpeak from "cpeak";
67
+ ```
68
+
69
+ Because of the minimalistic philosophy, you won’t add unnecessary objects to your memory as soon as you include the framework. If at any point you want to use a particular utility function (like `parseJSON` and `serveStatic`), include it like the line below, and only at that point will it be moved into memory:
70
+
71
+ ```javascript
72
+ import cpeak, { serveStatic, parseJSON } from "cpeak";
73
+ ```
74
+
75
+ ### Initializing
76
+
77
+ Initialize the Cpeak server like this:
78
+
79
+ ```javascript
80
+ const server = new cpeak();
81
+ ```
82
+
83
+ Now you can use this server object to start listening, add route logic, add middleware functions, and handle errors.
84
+
85
+ ### Middleware
86
+
87
+ If you add a middleware function, that function will run before your route logic kicks in. Here you can customize the request object, return an error, or do anything else you want to do prior to your route logic, like authentication.
88
+
89
+ After calling `next`, the next middleware function is going to run if there’s any; otherwise, the route logic is going to run.
90
+
91
+ ```javascript
92
+ server.beforeEach((req, res, next) => {
93
+ if (req.headers.authentication) {
94
+ // Your authentication logic...
95
+ req.userId = "<something>";
96
+ req.custom = "This is some string";
97
+ next();
98
+ } else {
99
+ // Return an error and close the request...
100
+ return res.status(401).json({ error: "Unauthorized" });
101
+ }
102
+ });
103
+
104
+ server.beforeEach((req, res, next) => {
105
+ console.log(
106
+ "The custom value was added from the previous middleware: ",
107
+ req.custom
108
+ );
109
+ next();
110
+ });
111
+ ```
112
+
113
+ ### Route Handling
114
+
115
+ You can add new routes like this:
116
+
117
+ ```javascript
118
+ server.route("patch", "/the-path-you-want", (req, res) => {
119
+ // your route logic
120
+ });
121
+ ```
122
+
123
+ First add the HTTP method name you want to handle, then the path, and finally, the callback. The `req` and `res` object types are the same as in the Node.js HTTP module (`http.IncomingMessage` and `http.ServerResponse`). You can read more about them in the [official Node.js documentation](https://nodejs.org/docs/latest/api/http.html).
124
+
125
+ ### URL Variables & Parameters
126
+
127
+ Since in HTTP these are called URL parameters: `/path?key1=value1&key2=value2&foo=900`, in Cpeak, we also call them `params` (short for HTTP URL parameters).
128
+ We can also do custom path management, and we call them `vars` (short for URL variables).
129
+
130
+ Here’s how we can read both:
131
+
132
+ ```javascript
133
+ // Imagine request URL is example.com/test/my-title/more-text?filter=newest
134
+ server.route("patch", "/test/:title/more-text", (req, res) => {
135
+ const title = req.vars.title;
136
+ const filter = req.params.filter;
137
+
138
+ console.log(title); // my-title
139
+ console.log(filter); // newest
140
+ });
141
+ ```
142
+
143
+ ### Sending Files
144
+
145
+ You can send a file as a Node.js Stream anywhere in your route or middleware logic like this:
146
+
147
+ ```javascript
148
+ server.route("get", "/testing", (req, res) => {
149
+ return res.status(200).sendFile("<file-path>", "<mime-type>");
150
+
151
+ // Example:
152
+ // return res.status(200).sendFile("./images/sun.jpeg", "image/jpeg");
153
+ });
154
+ ```
155
+
156
+ The file’s binary content will be in the HTTP response body content. Make sure you specify a correct path relative to your CWD (use the `path` module for better compatibility) and also the correct HTTP MIME type for that file.
157
+
158
+ ### Error Handling
159
+
160
+ If anywhere in your route functions you want to return an error, it's cleaner to pass it to the `handleErr` function like this:
161
+
162
+ ```javascript
163
+ server.route("get", "/api/document/:title", (req, res, handleErr) => {
164
+ const title = req.vars.title;
165
+
166
+ if (title.length > 500)
167
+ return handleErr({ status: 400, message: "Title too long." });
168
+
169
+ // The rest of your logic...
170
+ });
171
+ ```
172
+
173
+ And then handle all the errors like this in the `handleErr` callback:
174
+
175
+ ```javascript
176
+ server.handleErr((error, req, res) => {
177
+ if (error && error.status) {
178
+ res.status(error.status).json({ error: error.message });
179
+ } else {
180
+ // Log the unexpected errors somewhere so you can keep track of them...
181
+ console.error(error);
182
+ res.status(500).json({
183
+ error: "Sorry, something unexpected happened on our side.",
184
+ });
185
+ }
186
+ });
187
+ ```
188
+
189
+ The error object is the object that you passed to the `handleErr` function earlier in your routes.
190
+
191
+ ### Listening
192
+
193
+ Start listening on a specific port like this:
194
+
195
+ ```javascript
196
+ server.listen(3000, () => {
197
+ console.log("Server has started on port 3000");
198
+ });
199
+ ```
200
+
201
+ ### Util Functions
202
+
203
+ There are utility functions that you can include and use as middleware functions. These are meant to make it easier for you to build HTTP applications. In the future, many more will be added, and you only move them into memory once you include them. No need to have many npm dependencies for simple applications!
204
+
205
+ The list of utility functions as of now:
206
+
207
+ - serveStatic
208
+ - parseJSON
209
+
210
+ Including any one of them is done like this:
211
+
212
+ ```javascript
213
+ import cpeak, { utilName } from "cpeak";
214
+ ```
215
+
216
+ #### serveStatic
217
+
218
+ With this middleware function, you can automatically set a folder in your project to be served by Cpeak. Here’s how to set it up:
219
+
220
+ ```javascript
221
+ server.beforeEach(
222
+ serveStatic("./public", {
223
+ mp3: "audio/mpeg",
224
+ })
225
+ );
226
+ ```
227
+
228
+ If you have file types in your public folder that are not one of the following, make sure to add the MIME types manually as the second argument in the function as an object where each property key is the file extension, and each value is the correct MIME type for that. You can see all the available MIME types on the [IANA website](https://www.iana.org/assignments/media-types/media-types.xhtml).
229
+
230
+ ```
231
+ html: "text/html",
232
+ css: "text/css",
233
+ js: "application/javascript",
234
+ jpg: "image/jpeg",
235
+ jpeg: "image/jpeg",
236
+ png: "image/png",
237
+ svg: "image/svg+xml",
238
+ txt: "text/plain",
239
+ eot: "application/vnd.ms-fontobject",
240
+ otf: "font/otf",
241
+ ttf: "font/ttf",
242
+ woff: "font/woff",
243
+ woff2: "font/woff2"
244
+ ```
245
+
246
+ #### parseJSON
247
+
248
+ With this middleware function, you can easily read and send JSON in HTTP message bodies in route and middleware functions. Fire it up like this:
249
+
250
+ ```javascript
251
+ server.beforeEach(parseJSON);
252
+ ```
253
+
254
+ Read and send JSON from HTTP messages like this:
255
+
256
+ ```javascript
257
+ server.route("put", "/api/user", (req, res) => {
258
+ // Reading JSON from the HTTP request:
259
+ const email = req.body.email;
260
+
261
+ // rest of your logic...
262
+
263
+ // Sending JSON in the HTTP response:
264
+ res.status(201).json({ message: "Something was created..." });
265
+ });
266
+ ```
267
+
268
+ ## Complete Example
269
+
270
+ Here you can see all the features that Cpeak offers, in one small piece of code:
271
+
272
+ ```javascript
273
+ import cpeak, { serveStatic, parseJSON } from "cpeak";
274
+
275
+ const server = new cpeak();
276
+
277
+ server.beforeEach(
278
+ serveStatic("./public", {
279
+ mp3: "audio/mpeg",
280
+ })
281
+ );
282
+
283
+ // For parsing JSON bodies
284
+ server.beforeEach(parseJSON);
285
+
286
+ // Adding custom middleware functions
287
+ server.beforeEach((req, res, next) => {
288
+ req.custom = "This is some string";
289
+ next();
290
+ });
291
+
292
+ // Adding route handlers
293
+ server.route("get", "/api/document/:title", (req, res, handleErr) => {
294
+ // Reading URL variables
295
+ const title = req.vars.title;
296
+
297
+ // Reading URL parameters (like /users?filter=active)
298
+ const filter = req.params.filter;
299
+
300
+ // Reading JSON request body
301
+ const anything = req.body.anything;
302
+
303
+ // Handling errors
304
+ if (anything === "not-expected-thing")
305
+ return handleErr({ status: 400, message: "Invalid property." });
306
+
307
+ // Sending a JSON response
308
+ res.status(200).json({ message: "This is a test response" });
309
+ });
310
+
311
+ // Sending a file response
312
+ server.route("get", "/file", (req, res) => {
313
+ // Make sure to specify a correct path and MIME type...
314
+ res.status(200).sendFile("<path-to-file-relative-to-cwd>", "<mime-type>");
315
+ });
316
+
317
+ // Handle all the errors that could happen in the routes
318
+ server.handleErr((error, req, res) => {
319
+ if (error && error.status) {
320
+ res.status(error.status).json({ error: error.message });
321
+ } else {
322
+ console.error(error);
323
+ res.status(500).json({
324
+ error: "Sorry, something unexpected happened from our side.",
325
+ });
326
+ }
327
+ });
328
+
329
+ server.listen(3000, () => {
330
+ console.log("Server has started on port 3000");
331
+ });
332
+ ```
333
+
334
+ ## Versioning Notice
335
+
336
+ #### Version `1.x.x`
337
+
338
+ Version `1.x.x` represents the initial release of our framework, developed during the _Understanding Node.js Core Concepts_ course. These versions laid the foundation for our project.
339
+
340
+ #### Version `2.x.x`
341
+
342
+ All version `2.x.x` releases are considered to be in active development, following the completion of the course. These versions include ongoing feature additions and API changes as we refine the framework. Frequent updates may require code changes, so version `2.x.x` is not recommended for production environments.
343
+ For new features, bug fixes, and other changes that don't break existing code, the patch version will be increased. For changes that break existing code, the minor version will be increased.
344
+
345
+ #### Version `3.x.x`
346
+
347
+ Version `3.x.x` and beyond will be our first production-ready releases. These versions are intended for stable, long-term use, with a focus on backward compatibility and minimal breaking changes.
package/lib/index.js CHANGED
@@ -1,8 +1,9 @@
1
- const http = require("node:http");
2
- const fs = require("node:fs/promises");
1
+ import http from "node:http";
2
+ import fs from "node:fs/promises";
3
3
 
4
- const { parseJSON, serveStatic } = require("./util");
5
- class CPeak {
4
+ import { serveStatic, parseJSON } from "./util.js";
5
+
6
+ class Cpeak {
6
7
  constructor() {
7
8
  this.server = http.createServer();
8
9
  this.routes = {};
@@ -33,28 +34,37 @@ class CPeak {
33
34
  res.end(JSON.stringify(data));
34
35
  };
35
36
 
37
+ // Get the url without the URL parameters
36
38
  const urlWithoutParams = req.url.split("?")[0];
37
- req.params = new URLSearchParams(req.url.split("?")[1]);
38
39
 
39
40
  // Run all the middleware functions before we run the corresponding route
40
41
  const runMiddleware = (req, res, middleware, index) => {
41
42
  // Out exit point...
42
43
  if (index === middleware.length) {
43
- // If the routes object does not have a key of req.method + req.url, return 404
44
- if (!this.routes[req.method.toLocaleLowerCase() + urlWithoutParams]) {
45
- return res
46
- .status(404)
47
- .json({ error: `Cannot ${req.method} ${urlWithoutParams}` });
44
+ for (const route of this.routes[req.method.toLowerCase()]) {
45
+ const match = urlWithoutParams.match(route.regex);
46
+
47
+ if (match) {
48
+ // Parse the URL parameters (like /users?key1=value1&key2=value2)
49
+ const params = new URLSearchParams(req.url.split("?")[1]);
50
+ req.params = Object.fromEntries(params.entries());
51
+
52
+ // Parse the URL variables from the matched route (like /users/:id)
53
+ const vars = this.#extractVars(route.path, match);
54
+ req.vars = vars;
55
+
56
+ // Call the route handler with the modified req and res objects
57
+ return route.cb(req, res, (error) => {
58
+ res.setHeader("Connection", "close");
59
+ this.handleErr(error, req, res);
60
+ });
61
+ }
48
62
  }
49
63
 
50
- this.routes[req.method.toLowerCase() + urlWithoutParams](
51
- req,
52
- res,
53
- (error) => {
54
- res.setHeader("Connection", "close");
55
- this.handleErr(error, req, res);
56
- }
57
- );
64
+ // If the requested route dose not exist, return 404
65
+ return res
66
+ .status(404)
67
+ .json({ error: `Cannot ${req.method} ${urlWithoutParams}` });
58
68
  } else {
59
69
  middleware[index](req, res, () => {
60
70
  runMiddleware(req, res, middleware, index + 1);
@@ -67,7 +77,10 @@ class CPeak {
67
77
  }
68
78
 
69
79
  route(method, path, cb) {
70
- this.routes[method + path] = cb;
80
+ if (!this.routes[method]) this.routes[method] = [];
81
+
82
+ const regex = this.#pathToRegex(path);
83
+ this.routes[method].push({ path, regex, cb });
71
84
  }
72
85
 
73
86
  beforeEach(cb) {
@@ -83,9 +96,37 @@ class CPeak {
83
96
  cb();
84
97
  });
85
98
  }
99
+
100
+ // ------------------------------
101
+ // PRIVATE METHODS:
102
+ // ------------------------------
103
+ #pathToRegex(path) {
104
+ const varNames = [];
105
+ const regexString =
106
+ "^" +
107
+ path.replace(/:\w+/g, (match, offset) => {
108
+ varNames.push(match.slice(1));
109
+ return "([^/]+)";
110
+ }) +
111
+ "$";
112
+
113
+ const regex = new RegExp(regexString);
114
+ return regex;
115
+ }
116
+
117
+ #extractVars(path, match) {
118
+ // Extract url variable values from the matched route
119
+ const varNames = (path.match(/:\w+/g) || []).map((varParam) =>
120
+ varParam.slice(1)
121
+ );
122
+ const vars = {};
123
+ varNames.forEach((name, index) => {
124
+ vars[name] = match[index + 1];
125
+ });
126
+ return vars;
127
+ }
86
128
  }
87
129
 
88
- CPeak.parseJSON = parseJSON;
89
- CPeak.serveStatic = serveStatic;
130
+ export { serveStatic, parseJSON };
90
131
 
91
- module.exports = CPeak;
132
+ export default Cpeak;
package/lib/util.js CHANGED
@@ -1,5 +1,5 @@
1
- const fs = require("node:fs");
2
- const path = require("node:path");
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
3
 
4
4
  const MIME_TYPES = {
5
5
  html: "text/html",
@@ -17,7 +17,7 @@ const MIME_TYPES = {
17
17
  woff2: "font/woff2",
18
18
  };
19
19
 
20
- exports.serveStatic = (folderPath, newMimeTypes) => {
20
+ const serveStatic = (folderPath, newMimeTypes) => {
21
21
  // For new user defined mime types
22
22
  if (newMimeTypes) {
23
23
  Object.assign(MIME_TYPES, newMimeTypes);
@@ -75,7 +75,7 @@ exports.serveStatic = (folderPath, newMimeTypes) => {
75
75
  };
76
76
 
77
77
  // Parsing JSON
78
- exports.parseJSON = (req, res, next) => {
78
+ const parseJSON = (req, res, next) => {
79
79
  // This is only good for bodies that their size is less than the highWaterMark value
80
80
  if (req.headers["content-type"] === "application/json") {
81
81
  let body = "";
@@ -92,3 +92,5 @@ exports.parseJSON = (req, res, next) => {
92
92
  next();
93
93
  }
94
94
  };
95
+
96
+ export { serveStatic, parseJSON };
package/package.json CHANGED
@@ -1,11 +1,26 @@
1
1
  {
2
2
  "name": "cpeak",
3
- "version": "1.4.0",
4
- "description": "",
3
+ "version": "2.2.0",
4
+ "description": "A minimal and fast Node.js HTTP framework.",
5
+ "type": "module",
5
6
  "main": "./lib/index.js",
6
7
  "scripts": {
7
8
  "test": "echo \"Error: no test specified\" && exit 1"
8
9
  },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/agile8118/cpeak.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/agile8118/cpeak/issues"
16
+ },
17
+ "homepage": "https://github.com/agile8118/cpeak#readme",
9
18
  "author": "Cododev Technology",
10
- "license": "ISC"
19
+ "license": "MIT",
20
+ "keywords": [
21
+ "cpeak",
22
+ "nodejs",
23
+ "http",
24
+ "framework"
25
+ ]
11
26
  }