update promises with async/await --' + add printf() support and make the flow more understandable

This commit is contained in:
Adrien Marquès 2018-10-24 08:58:23 +02:00
parent 9b7e1f6e67
commit f0694a6b55
4 changed files with 53 additions and 52 deletions

View File

@ -1,26 +1,26 @@
import Client from "./interface"; import Client from "./interface";
import Key from "./keys"; import Key from "./keys";
import { request } from 'https'; import { request } from 'https';
import printf from "../fmt/printf";
export default class CarrefourItems implements Client { export default class CarrefourItems implements Client {
host: string; static host: string = 'api.fr.carrefour.io';
uri: string; static uri: string = '/v1/openapi/items';
token: string; static get key(){ return Key.get('carrefour'); }
clients: any[];
static get key(){ return Key.get("carrefour"); }
constructor(){ constructor(){
this.host = "api.fr.carrefour.io"; printf('+ carrefour items \t-> ');
this.uri = "/v1/openapi/items";
// check key // 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']"); throw new Error("The 'carrefour' key must feature 2 fields: ['app_id', 'app_secret']");
} }
printf('loaded\n');
}
call(query: object|string) : Promise<object>{ call(query: object|string) : Promise<object>{
@ -33,8 +33,8 @@ export default class CarrefourItems implements Client {
}) })
let reqopt = { let reqopt = {
hostname: this.host, hostname: CarrefourItems.host,
path: this.uri, path: CarrefourItems.uri,
port: 443, port: 443,
method: 'POST', method: 'POST',
headers: { headers: {
@ -48,6 +48,8 @@ export default class CarrefourItems implements Client {
return new Promise<object>( (resolve, reject) => { return new Promise<object>( (resolve, reject) => {
printf(' + carrefour item search | ');
let req = request(reqopt, (res) => { let req = request(reqopt, (res) => {
let chunks = []; let chunks = [];

7
src/fmt/printf.ts Normal file
View File

@ -0,0 +1,7 @@
import { format } from "util";
export default function printf(fmt:string, ...options:any){
process.stdout.write( format(fmt, ...options) );
}

View File

@ -2,11 +2,11 @@ import { createServer } from 'http'
import { Socket } from 'net'; import { Socket } from 'net';
import Mixer from './mixer' import Mixer from './mixer'
import CarrefourItems from './api/items'; import CarrefourItems from './api/items';
import printf from './fmt/printf';
const mixer: Mixer = new Mixer(); const mixer: Mixer = new Mixer();
// 1. build server // 1. build server
const server = createServer(mixer.http_handler.bind(mixer)); const server = createServer(mixer.http_handler.bind(mixer));
@ -17,4 +17,4 @@ server.on('clientError', (err: Error, sock: Socket) => {
// 3. listen on given port // 3. listen on given port
server.listen(8000); server.listen(8000);
console.log('+ listen 8080') printf('+ listen 8080\n')

View File

@ -3,15 +3,16 @@ import CarrefourItems from "./api/items";
import { parse as parseURL, UrlWithParsedQuery } from "url"; import { parse as parseURL, UrlWithParsedQuery } from "url";
import { ParsedUrlQuery } from "querystring"; import { ParsedUrlQuery } from "querystring";
import Client from "./api/interface"; import Client from "./api/interface";
import printf from "./fmt/printf";
export default class Mixer { export default class Mixer {
static valid_urls = ["/", "/oauth"]; static valid_urls = ["/"];
chain: Client[] = [new CarrefourItems()]; chain: Client[] = [new CarrefourItems()];
constructor(){ constructor(){
console.log("+ mixer init"); printf('+ mixer \t\t-> loaded\n\n');
} }
http_handler(req: IncomingMessage, res: ServerResponse){ http_handler(req: IncomingMessage, res: ServerResponse){
@ -29,51 +30,42 @@ export default class Mixer {
return; return;
} }
// if query this.query(req, res).then((obj) => {
if( urlObj.pathname == "/" ){
let err:Error = this.query(req, res); res.end(JSON.stringify(obj));
if( err != null ){
}).catch( err => {
res.writeHead(200, { 'Content-Type': 'application/json' }) res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({reason: `query error: ${err.toString()}`})) res.end(JSON.stringify({reason: `query error: ${err.toString()}`}))
}
return;
// 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()}`}))
}
}
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)
}) })
return null; }
async query(req: IncomingMessage, res: ServerResponse) : Promise<object>{
let query: ParsedUrlQuery = parseURL(req.url,true).query
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
}
} }
oauth(req: IncomingMessage, res: ServerResponse) : Error{ return out;
console.log(`oauth(${req},${res})`);
let query: ParsedUrlQuery = parseURL(req.url,true).query
console.log('query is:', query);
return new Error('OAuth error');
} }
} }