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 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');
}
call(query: object|string) : Promise<object>{
@ -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<object>( (resolve, reject) => {
printf(' + carrefour item search | ');
let req = request(reqopt, (res) => {
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 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')
printf('+ listen 8080\n')

View File

@ -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 ){
this.query(req, res).then((obj) => {
res.end(JSON.stringify(obj));
}).catch( err => {
res.writeHead(200, { 'Content-Type': 'application/json' })
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;
}
oauth(req: IncomingMessage, res: ServerResponse) : Error{
console.log(`oauth(${req},${res})`);
async query(req: IncomingMessage, res: ServerResponse) : Promise<object>{
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;
}
}