Skip to content

Commit

Permalink
feat: Updated CRUD router to handle POST requests, modified request J…
Browse files Browse the repository at this point in the history
…SON parsing, and refactored server and router logic.
  • Loading branch information
m-mdy-m committed Aug 20, 2024
1 parent a3e00bb commit cec3fdc
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 14 deletions.
17 changes: 13 additions & 4 deletions examples/CRUD/router/crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,26 @@ import { exposed } from '../../../lib/core/decorators/exposed';
import { Delete, Get, Post, Put, Route } from '../../../lib/core/router';
import { Context } from '../../../lib/types/types';
import db from '../models/db.json';
import fs from 'fs';
import p from 'path';
const file = p.join(__dirname, '..', 'models', 'db.json');
@Route('/')
@exposed
class GetAllUser {
class CRUD {
@Get()
get(ctx: Context) {
const users = JSON.stringify(db);
ctx.write(users);
ctx.end();
ctx.writeHead(200, {
'Content-Length': Buffer.byteLength(users),
'Content-Type': 'text/plain',
});
ctx.end(users);
}
@Post()
post(ctx: Context) {}
post(ctx: Context) {
const user = ctx.body
console.log('use:', user);
}
@Delete()
del(ctx: Context) {}
@Put()
Expand Down
14 changes: 12 additions & 2 deletions lib/core/router/request.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { IncomingMessage } from 'http';
import { logger } from '../../helper/logger';
const PROTO = IncomingMessage.prototype;
PROTO.json = function (): Promise<object> {
PROTO.json = function (): Promise<object | undefined> {
return new Promise((resolve, reject) => {
let body = '';
this.on('data', (chunk) => {
body += chunk;
});
this.on('end', () => {
resolve(JSON.parse(body));
if (!body) {
logger.warn('Request body is empty.');
resolve(undefined);
} else {
try {
resolve(JSON.parse(body));
} catch (error) {
reject(new Error('Invalid JSON format.'));
}
}
});
this.on('error', (error) => {
reject(error);
Expand Down
7 changes: 0 additions & 7 deletions lib/core/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export class WebServer extends Server implements Gland.Listener, Gland.APP {
} else {
throw new Error('Invalid middleware/handler function signature');
}
console.log('middlewares', this.middlewares);
});
} else {
// If the first argument is not a string, treat it as a middleware
Expand Down Expand Up @@ -80,14 +79,8 @@ export class WebServer extends Server implements Gland.Listener, Gland.APP {
ctx.params = params;
// Check if the controller is a class or a function
if (typeof controller === 'function' && !handlerKey) {
this.middlewares.forEach((fn, index) => {
console.log(`Middleware ${index + 1}:`, fn.name || fn.toString());
});
const middlewareStack = Array.from(new Set([...this.middlewares, controller]));
// Logging the function names or sources to help identify duplication
// middlewareStack.forEach((fn, index) => {
// console.log(`Middleware ${index + 1}:`, fn.name || fn.toString());
// });
await Router.execute(ctx, middlewareStack);
} else {
const routeInstance = new controller();
Expand Down
2 changes: 1 addition & 1 deletion lib/types/http.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { IncomingMessage, ServerResponse } from 'http';

declare module 'http' {
interface IncomingMessage {
json(): Promise<object>;
json(): Promise<object | undefined>;
get(header: string): string | undefined;
path(): string;
hostname(): string;
Expand Down

0 comments on commit cec3fdc

Please sign in to comment.