-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_deno.ts
187 lines (166 loc) · 5.49 KB
/
main_deno.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Simplified Mock API Application with Config File (Deno Version)
// import {Application, Context} from "https://deno.land/x/oak/mod.ts";
import {resolve} from "https://deno.land/std/path/mod.ts";
import {parse} from "https://deno.land/std/yaml/mod.ts"; // For parsing YAML
import {DB} from "https://deno.land/x/sqlite/mod.ts"; // Deno SQLite library
interface ApiEndpoint {
method: string;
path: string;
response: Record<string, any>;
statusCode: number;
}
class ApiDefinitionLoader {
private apiEndpoints: Record<string, ApiEndpoint>;
constructor(configFile: string) {
this.apiEndpoints = this.loadApiDefinitions(configFile);
}
public getApiEndpoints(): Record<string, ApiEndpoint> {
return this.apiEndpoints;
}
private loadApiDefinitions(
configFile: string,
): Record<string, ApiEndpoint> {
try {
const fileContent = Deno.readTextFileSync(resolve(configFile));
return parse(fileContent) as Record<string, ApiEndpoint>;
} catch (error) {
console.error("Failed to load API definitions:", error);
throw new Error("Failed to load API definitions");
}
}
}
class Logger {
private db: DB;
constructor(dbName: string) {
this.db = new DB(dbName);
this.createTable();
}
private createTable() {
this.db.query(`
CREATE TABLE IF NOT EXISTS api_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
request_method TEXT,
request_path TEXT,
request_query TEXT,
request_headers TEXT,
request_body TEXT,
response_status_code INTEGER,
response_body TEXT
)
`);
}
public log(logData: any) {
const { timestamp, request, response } = logData;
const { method, path, query, headers, body } = request;
const { statusCode, body: responseBody } = response;
const sql = `
INSERT INTO api_logs (timestamp, request_method, request_path, request_query, request_headers, request_body, response_status_code, response_body)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`;
this.db.query(sql, [
timestamp,
method,
path,
JSON.stringify(query),
JSON.stringify(headers),
JSON.stringify(body),
statusCode,
JSON.stringify(responseBody),
]);
}
}
//const app = new Application();
const DEFAULT_PORT = 8000;
const portArg = Deno.args.find((arg) => arg.startsWith("--port="));
const PORT = portArg ? parseInt(portArg.split("=")[1], 10) : DEFAULT_PORT;
const LOG_FILE = "server.log";
const apiDefinitionLoader = new ApiDefinitionLoader("api_definitions.yaml");
const apiEndpoints = apiDefinitionLoader.getApiEndpoints();
const logger = new Logger("api_logs.db");
// Middleware to handle logging
// app.use(async (context: Context) => {
// const { request, response } = context;
// const path = request.url.pathname;
// const method = request.method.toUpperCase();
// const key = `${method} ${path}`;
//
// const endpoint = apiEndpoints[key];
//
// if (!endpoint) {
// response.status = 404;
// response.body = "Endpoint not found";
// return;
// }
//
// const logData = {
// timestamp: new Date().toISOString(),
// request: {
// method: request.method,
// path: request.url.pathname,
// query: request.url.searchParams,
// headers: request.headers,
// body: await request.body.text(),
// },
// response: {
// statusCode: endpoint.statusCode,
// body: endpoint.response,
// },
// };
//
// logger.log(logData);
//
// response.status = endpoint.statusCode;
// response.body = endpoint.response;
// });
//
// app.use(router.routes());
// app.use(router.allowedMethods());
Deno.serve({ port: PORT, hostname: "0.0.0.0" }, async (request) => {
// const { request, response } = context;
const url = new URL(request.url);
const path = url.pathname;
const method = request.method.toUpperCase();
const key = `${method} ${path}`;
const endpoint = apiEndpoints[key];
if (!endpoint) {
return new Response("Endpoint not found", { status: 404 });
}
const logData = {
timestamp: new Date().toISOString(),
request: {
method: request.method,
path: url.pathname,
query: url.searchParams,
headers: request.headers,
body: await request.text(),
},
response: {
statusCode: endpoint.statusCode,
body: endpoint.response,
},
};
// response.status = endpoint.statusCode;
// response.body = endpoint.response;
return new Response(JSON.stringify(endpoint.response), {
status: endpoint.statusCode,
headers: {
"content-type": "application/json; charset=utf-8",
},
});
});
// console.log(`Mock API server running at http://localhost:${PORT}`);
// await .listen({ port: PORT });
// Config File Example (api_definitions.yaml):
// GET /api/data:
// method: GET
// path: /api/data
// response:
// message: "Mock data fetched successfully!"
// statusCode: 200
// POST /api/data:
// method: POST
// path: /api/data
// response:
// message: "Mock data posted successfully!"
// statusCode: 201