From f0694a6b551bd5a2d705ebfcbba58c9b3fa848be Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Wed, 24 Oct 2018 08:58:23 +0200 Subject: [PATCH] update promises with async/await --' + add printf() support and make the flow more understandable --- src/api/items.ts | 26 +++++++++--------- src/fmt/printf.ts | 7 +++++ src/main.ts | 4 +-- src/mixer.ts | 68 +++++++++++++++++++++-------------------------- 4 files changed, 53 insertions(+), 52 deletions(-) create mode 100644 src/fmt/printf.ts diff --git a/src/api/items.ts b/src/api/items.ts index d6fe9b8..19e9a0b 100644 --- a/src/api/items.ts +++ b/src/api/items.ts @@ -1,24 +1,24 @@ import Client from "./interface"; import Key from "./keys"; import { request } from 'https'; +import printf from "../fmt/printf"; export default class CarrefourItems implements Client { - host: string; - uri: string; - token: string; - clients: any[]; - - static get key(){ return Key.get("carrefour"); } - + static host: string = 'api.fr.carrefour.io'; + static uri: string = '/v1/openapi/items'; + static get key(){ return Key.get('carrefour'); } constructor(){ - this.host = "api.fr.carrefour.io"; - this.uri = "/v1/openapi/items"; + printf('+ carrefour items \t-> '); // check key - if( !CarrefourItems.key['app_id'] || !CarrefourItems.key['app_secret'] ) + if( !CarrefourItems.key['app_id'] || !CarrefourItems.key['app_secret'] ){ + printf('error\n'); throw new Error("The 'carrefour' key must feature 2 fields: ['app_id', 'app_secret']"); + } + + printf('loaded\n'); } @@ -33,8 +33,8 @@ export default class CarrefourItems implements Client { }) let reqopt = { - hostname: this.host, - path: this.uri, + hostname: CarrefourItems.host, + path: CarrefourItems.uri, port: 443, method: 'POST', headers: { @@ -48,6 +48,8 @@ export default class CarrefourItems implements Client { return new Promise( (resolve, reject) => { + printf(' + carrefour item search | '); + let req = request(reqopt, (res) => { let chunks = []; diff --git a/src/fmt/printf.ts b/src/fmt/printf.ts new file mode 100644 index 0000000..878b610 --- /dev/null +++ b/src/fmt/printf.ts @@ -0,0 +1,7 @@ +import { format } from "util"; + +export default function printf(fmt:string, ...options:any){ + + process.stdout.write( format(fmt, ...options) ); + +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 5a3173c..6d4dcf0 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,11 +2,11 @@ import { createServer } from 'http' import { Socket } from 'net'; import Mixer from './mixer' import CarrefourItems from './api/items'; +import printf from './fmt/printf'; const mixer: Mixer = new Mixer(); - // 1. build server const server = createServer(mixer.http_handler.bind(mixer)); @@ -17,4 +17,4 @@ server.on('clientError', (err: Error, sock: Socket) => { // 3. listen on given port server.listen(8000); -console.log('+ listen 8080') \ No newline at end of file +printf('+ listen 8080\n') \ No newline at end of file diff --git a/src/mixer.ts b/src/mixer.ts index 365c1f0..4a20ab8 100644 --- a/src/mixer.ts +++ b/src/mixer.ts @@ -3,15 +3,16 @@ import CarrefourItems from "./api/items"; import { parse as parseURL, UrlWithParsedQuery } from "url"; import { ParsedUrlQuery } from "querystring"; import Client from "./api/interface"; +import printf from "./fmt/printf"; export default class Mixer { - static valid_urls = ["/", "/oauth"]; + static valid_urls = ["/"]; chain: Client[] = [new CarrefourItems()]; constructor(){ - console.log("+ mixer init"); + printf('+ mixer \t\t-> loaded\n\n'); } http_handler(req: IncomingMessage, res: ServerResponse){ @@ -29,51 +30,42 @@ export default class Mixer { return; } - // if query - if( urlObj.pathname == "/" ){ - let err:Error = this.query(req, res); - if( err != null ){ - res.writeHead(200, { 'Content-Type': 'application/json' }) - res.end(JSON.stringify({reason: `query error: ${err.toString()}`})) - } + this.query(req, res).then((obj) => { - return; + res.end(JSON.stringify(obj)); - // if oauth - } else { - let err:Error = this.oauth(req, res); - if( err != null ){ - res.writeHead(200, { 'Content-Type': 'application/json' }) - res.end(JSON.stringify({reason: `query error: ${err.toString()}`})) - } - } + }).catch( err => { - res.end(); - } - - - query(req: IncomingMessage, res: ServerResponse) : Error{ - - let query: ParsedUrlQuery = parseURL(req.url,true).query - - this.chain[0].call(query['q']).then( (obj:object) => { - console.log('query success') res.writeHead(200, { 'Content-Type': 'application/json' }) - res.end(JSON.stringify(obj)) - return null; - }).catch( (err:Error) => { - console.log('query error', err) + res.end(JSON.stringify({reason: `query error: ${err.toString()}`})) + }) - return null; - } - oauth(req: IncomingMessage, res: ServerResponse) : Error{ - console.log(`oauth(${req},${res})`); + + async query(req: IncomingMessage, res: ServerResponse) : Promise{ + let query: ParsedUrlQuery = parseURL(req.url,true).query - console.log('query is:', query); - return new Error('OAuth error'); + let out: any[] = []; + + for( let i = 0 ; i < this.chain.length ; i++ ){ + + let input = (i<1) ? query['q'] : out[i-1]; + + try { + out[i] = await this.chain[i].call(input) + printf('ok\n') + + }catch(e){ + printf('fail\n'); + throw e + } + + } + + return out; + } } \ No newline at end of file