GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor: api url parse + override json response · eas-framework/eas-framework@3dcdac0

This repository was archived by the owner on Oct 6, 2024. It is now read-only.

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • BuildInComponents/Components
      • connect.ts
    • CompileCode
      • InsertComponent.ts
      • InsertModels.ts
    • MainBuild
      • Server.ts
    • Plugins
      • HTTP.ts
      • HTTP
        • Response.ts
      • Syntax.ts
    • RunTimeBuild
      • ApiCall.ts
  • tests/core/Website/WWW/server/api
    • search.api.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/BuildInComponents/Components/connect.ts‎

Copy file name to clipboardExpand all lines: src/BuildInComponents/Components/connect.ts
+4-9Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export function addFinalizeBuild(pageData: StringTracker, sessionInfo: SessionBu
5050
message:${typeof i.message == 'string' ? `"${i.message}"` : i.message},
5151
validator:[${(i.validator && i.validator.map(compileValues).join(',')) || ''}]
5252
}`
53-
}, {returnData: true})
53+
}, { returnData: true })
5454
}
5555

5656
export async function handelConnector(thisPage: any, connector: any) {
@@ -59,19 +59,14 @@ export async function handelConnector(thisPage: any, connector: any) {
5959

6060
thisPage.setResponse('');
6161

62-
const betterJSON = (obj: any) => {
63-
thisPage.Response.setHeader('Content-Type', 'application/json');
64-
thisPage.Response.end(JSON.stringify(obj));
65-
}
66-
6762
if (!connector.validator.length || isValid === true)
68-
betterJSON(await connector.sendTo(...values));
63+
thisPage.Response.json(await connector.sendTo(...values));
6964

7065
else if (connector.notValid)
71-
betterJSON(await connector.notValid(...<any>isValid));
66+
thisPage.Response.json(await connector.notValid(...<any>isValid));
7267

7368
else if (connector.message)
74-
betterJSON({
69+
thisPage.Response.json({
7570
error: typeof connector.message == 'string' ? connector.message : (<any>isValid).shift()
7671
});
7772
else
Collapse file

‎src/CompileCode/InsertComponent.ts‎

Copy file name to clipboardExpand all lines: src/CompileCode/InsertComponent.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { BasicSettings } from '../RunTimeBuild/SearchFileSystem';
33
import { ParseDebugInfo, CreateFilePath, PathTypes, AddDebugInfo } from './XMLHelpers/CodeInfoAndDebug';
44
import { AllBuildIn, IsInclude, StartCompiling } from '../BuildInComponents/index';
55
import StringTracker, { StringTrackerDataInfo, ArrayMatch } from '../EasyDebug/StringTracker';
6-
import AddPlugin from '../Plugins/Index';
6+
import AddPlugin from '../Plugins/Syntax';
77
import {CompileInFileFunc, StringArrayOrObject, StringAnyMap } from './XMLHelpers/CompileTypes';
88
import { createNewPrint } from '../OutputInput/Logger';
99
import { InsertComponentBase, BaseReader, pool } from './BaseReader/Reader';
Collapse file

‎src/CompileCode/InsertModels.ts‎

Copy file name to clipboardExpand all lines: src/CompileCode/InsertModels.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { BasicSettings } from '../RunTimeBuild/SearchFileSystem';
33
import { print } from '../OutputInput/Console';
44
import InsertComponent from './InsertComponent';
55
import { PageTemplate } from './ScriptTemplate';
6-
import AddPlugin from '../Plugins/Index';
6+
import AddPlugin from '../Plugins/Syntax';
77
import { CreateFilePath, ParseDebugLine, AddDebugInfo } from './XMLHelpers/CodeInfoAndDebug';
88
import * as extricate from './XMLHelpers/Extricate';
99
import StringTracker from '../EasyDebug/StringTracker';
Collapse file

‎src/MainBuild/Server.ts‎

Copy file name to clipboardExpand all lines: src/MainBuild/Server.ts
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { BasicSettings } from '../RunTimeBuild/SearchFileSystem';
88
import formidable from 'formidable';
99
import { UpdateGreenLock } from './ListenGreenLock';
1010
import http from 'http';
11+
import updateRequestAttributes from '../Plugins/HTTP';
1112

1213

1314
async function requestAndSettings(req: Request, res: Response) {
@@ -93,6 +94,8 @@ async function StartApp(Server?) {
9394
* @param {Response} res - Response
9495
*/
9596
async function ParseRequest(req: Request, res: Response) {
97+
updateRequestAttributes(req, res);
98+
9699
if (req.method == 'POST') {
97100
if (req.headers['content-type']?.startsWith?.('application/json')) {
98101
Settings.middleware.bodyParser(req, res, () => requestAndSettings(req, res));
Collapse file

‎src/Plugins/HTTP.ts‎

Copy file name to clipboard
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { Request, Response } from "../MainBuild/Types";
2+
import updateResponse from "./HTTP/Response";
3+
4+
export default function updateRequestAttributes(req: Request, res: Response){
5+
updateResponse(res);
6+
}
Collapse file

‎src/Plugins/HTTP/Response.ts‎

Copy file name to clipboard
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { Response } from "../../MainBuild/Types";
2+
3+
function json(data: any){
4+
this.setHeader('Content-Type', 'application/json');
5+
this.end(JSON.stringify(data));
6+
return this
7+
}
8+
9+
export default function updateResponse(response: Response) {
10+
response.json = json;
11+
}
Collapse file

‎src/Plugins/Index.ts‎ ‎src/Plugins/Syntax.ts‎src/Plugins/Index.ts renamed to src/Plugins/Syntax.ts

Copy file name to clipboard
File renamed without changes.
Collapse file

‎src/RunTimeBuild/ApiCall.ts‎

Copy file name to clipboardExpand all lines: src/RunTimeBuild/ApiCall.ts
+20-32Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ async function makeDefinition(obj: any, urlFrom: string, defineObject: any, Requ
213213
*/
214214
async function MakeCall(fileModule: any, Request: any, Response: any, urlFrom: string, isDebug: boolean, nextPrase: () => Promise<any>) {
215215
const allowErrorInfo = !GetPlugin("SafeDebug") && isDebug, makeMassage = (e: any) => (isDebug ? print.error(e) : null) + (allowErrorInfo ? `, message: ${e.message}` : '');
216+
216217
const method = Request.method;
217218
let methodObj = fileModule[method] || fileModule.default[method]; //Loading the module by method
218219
let haveMethod = true;
@@ -223,42 +224,29 @@ async function MakeCall(fileModule: any, Request: any, Response: any, urlFrom: s
223224
}
224225

225226
const baseMethod = methodObj;
226-
227227
const defineObject = {};
228228

229-
const dataDefine = await makeDefinition(methodObj, urlFrom, defineObject, Request, Response, makeMassage); // root level definition
230-
if((<any>dataDefine).error) return Response.json(dataDefine);
231-
urlFrom = <string>dataDefine;
229+
let nestedURL: string;
232230

233-
let nestedURL = findBestUrlObject(methodObj, urlFrom);
234-
235-
//parse the url path
236-
for(let i = 0; i< 2; i++){
237-
while ((nestedURL = findBestUrlObject(methodObj, urlFrom))) {
238-
const dataDefine = await makeDefinition(methodObj, urlFrom, defineObject, Request, Response, makeMassage);
239-
if((<any>dataDefine).error) return Response.json(dataDefine);
240-
urlFrom = <string>dataDefine;
241-
242-
urlFrom = trimType('/', urlFrom.substring(nestedURL.length));
231+
do { //parse the url path
232+
if(nestedURL){
243233
methodObj = methodObj[nestedURL];
234+
urlFrom = trimType('/', urlFrom.substring(nestedURL.length));
244235
}
236+
237+
const dataDefine = await makeDefinition(methodObj, urlFrom, defineObject, Request, Response, makeMassage);
238+
if((<any>dataDefine).error) return Response.json(dataDefine);
245239

246-
if(!haveMethod){ // check if that a method
247-
haveMethod = true;
248-
methodObj = methodObj[method];
249-
}
250-
}
240+
urlFrom = <string>dataDefine;
241+
} while(nestedURL = findBestUrlObject(methodObj, urlFrom));
251242

252243
methodObj = methodObj?.func && methodObj || baseMethod; // if there is an 'any' method
253-
254-
255244
if (!methodObj?.func)
256245
return false;
257246

258-
const leftData = urlFrom.split('/');
247+
const leftData = urlFrom ? urlFrom.split('/'): [];
259248
const urlData = [];
260249

261-
262250
let error: string;
263251
if (methodObj.validateURL) {
264252
for (const [index, validate] of Object.entries(methodObj.validateURL)) {
@@ -274,6 +262,7 @@ async function MakeCall(fileModule: any, Request: any, Response: any, urlFrom: s
274262
} else
275263
urlData.push(...leftData);
276264

265+
277266
if (!error && methodObj.validateFunc) {
278267
let validate: any;
279268
try {
@@ -292,26 +281,25 @@ async function MakeCall(fileModule: any, Request: any, Response: any, urlFrom: s
292281
return Response.json({ error });
293282

294283
const finalStep = await nextPrase(); // parse data from methods - post, get... + cookies, session...
295-
296-
let apiResponse: any, newResponse: any;
284+
let apiResponse: any;
297285
try {
298286
apiResponse = await methodObj.func(Request, Response, urlData, defineObject, leftData);
299287
} catch (e) {
300288
if (allowErrorInfo)
301-
newResponse = { error: e.message }
289+
apiResponse = { error: e.message }
302290
else
303-
newResponse = { error: '500 - Internal Server Error' };
291+
apiResponse = { error: '500 - Internal Server Error' };
304292
}
305293

306294
if (typeof apiResponse == 'string')
307-
newResponse = { text: apiResponse };
308-
else
309-
newResponse = apiResponse || newResponse;
295+
apiResponse = { text: apiResponse };
310296

311297
finalStep(); // save cookies + code
312298

313-
if (newResponse != null)
314-
Response.json(newResponse);
299+
if (apiResponse != null) // the response handled on the method
300+
Response.json(apiResponse);
301+
else if(!Response.finished) // the response is already sent
302+
Response.end()
315303

316304
return true;
317305
}
Collapse file

‎tests/core/Website/WWW/server/api/search.api.ts‎

Copy file name to clipboard
+18-3Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,30 @@
1-
import {SearchRecord} from '@eas-framework/server'
1+
import { SearchRecord } from '@eas-framework/server'
22

33
const docSearch = new SearchRecord('records/search.serv')
44
await docSearch.load()
55

6+
const mapResult = (d: any[]) => d.map(x => ({ text: x.text, link: x.link }))
7+
68
export default {
79
GET: {
810
define: {
911
query: String
1012
},
11-
func (Request, Response, _, {query}){
12-
return docSearch.search(query, {length: 15}).map(x => ({text: x.text, link: x.link}))
13+
count: {
14+
define: {
15+
number: Number
16+
},
17+
func(Request, Response, _, { query, number }) {
18+
return Math.min(number, mapResult(docSearch.search(query, { length: 15 })).length)
19+
}
20+
},
21+
first: {
22+
func(Request, Response, _, { query }) {
23+
return mapResult(docSearch.search(query, { length: 15 })).pop() || 'Not found'
24+
}
25+
},
26+
func(Request, Response, _, { query }) {
27+
return mapResult(docSearch.search(query, { length: 15 }))
1328
}
1429
}
1530
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.