From 9b7e1f6e672d1838c8bbb77ec523af488142c625 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Tue, 23 Oct 2018 20:59:33 +0200 Subject: [PATCH] works with Carrefour.Items api --- package.json | 4 --- src/api/interface.ts | 26 +++------------ src/api/items.ts | 79 ++++++++++++++++++++++++++++++++++++++++++++ src/main.ts | 2 +- src/mixer.ts | 25 ++++++++++---- tsconfig.json | 7 ++-- 6 files changed, 107 insertions(+), 36 deletions(-) create mode 100644 src/api/items.ts diff --git a/package.json b/package.json index 626f0af..7f9c7ed 100644 --- a/package.json +++ b/package.json @@ -9,12 +9,8 @@ "url": "https://git.xdrm.io/MTI/api-mixer.js" }, "main": "dist/main.js", - "dependencies": { - "request": "^2.88.0" - }, "devDependencies": { "@types/node": "^10.12.0", - "@types/request": "^2.47.1", "typescript": "^3.1.3" }, "scripts": { diff --git a/src/api/interface.ts b/src/api/interface.ts index 173e29f..3faedd9 100644 --- a/src/api/interface.ts +++ b/src/api/interface.ts @@ -1,28 +1,10 @@ export default interface Client { - - /** Processes an API call to the given resource and returns a Promise with the - * error description OR the result data as JSON + /** Processes an API call to the given resource and returns a Promise resolving with the output object + * or rejecting the Error * - * @param method the HTTP METHOD to use - * @param path The API path - * @param params The API-specific options + * @param query represents the input data composing the request */ - call(method: HTTP_METHOD, path: String, params?: Parameters) : Promise; + call(query: object|string) : Promise; -} - - -// Defines HTTP methods subset -export enum HTTP_METHOD { - GET, - POST, - PUT, - DELETE -} - -export class Parameters{ - get: object; - post: object; - constructor(){ this.get = {}; this.post = {}; } } \ No newline at end of file diff --git a/src/api/items.ts b/src/api/items.ts new file mode 100644 index 0000000..d6fe9b8 --- /dev/null +++ b/src/api/items.ts @@ -0,0 +1,79 @@ +import Client from "./interface"; +import Key from "./keys"; +import { request } from 'https'; + +export default class CarrefourItems implements Client { + + host: string; + uri: string; + token: string; + clients: any[]; + + static get key(){ return Key.get("carrefour"); } + + + constructor(){ + this.host = "api.fr.carrefour.io"; + this.uri = "/v1/openapi/items"; + + // check key + if( !CarrefourItems.key['app_id'] || !CarrefourItems.key['app_secret'] ) + throw new Error("The 'carrefour' key must feature 2 fields: ['app_id', 'app_secret']"); + } + + + call(query: object|string) : Promise{ + + // check query + if( typeof query != 'string' ) + return new Promise((_,reject)=>{ reject('invalid query; expected string') }) + + let reqdata = JSON.stringify({ + queries: [ { query: query, field: 'barcodeDescription' } ] + }) + + let reqopt = { + hostname: this.host, + path: this.uri, + port: 443, + method: 'POST', + headers: { + 'Accept': 'application/json', + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(reqdata), + 'x-ibm-client-id': CarrefourItems.key['app_id'], + 'x-ibm-client-secret': CarrefourItems.key['app_secret'], + } + }; + + return new Promise( (resolve, reject) => { + + let req = request(reqopt, (res) => { + + let chunks = []; + + res.on('data', (chunk) => chunks.push(chunk)); + + res.on('end', () => { + let raw = Buffer.concat(chunks) + try{ + let json = JSON.parse(raw.toString()); + resolve(json) + }catch(e){ + reject(`invalid json response: ${e.message}`); + } + + }); + + }) + + req.on('error', (err) => reject(err.message)); + req.write(reqdata); + req.end(); + + + }); + } + + +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 300d8c5..5a3173c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,7 +8,7 @@ const mixer: Mixer = new Mixer(); // 1. build server -const server = createServer(mixer.http_handler); +const server = createServer(mixer.http_handler.bind(mixer)); // 2. bind 404 error server.on('clientError', (err: Error, sock: Socket) => { diff --git a/src/mixer.ts b/src/mixer.ts index b454d6f..365c1f0 100644 --- a/src/mixer.ts +++ b/src/mixer.ts @@ -2,15 +2,16 @@ import { IncomingMessage, ServerResponse, Server } from "http"; import CarrefourItems from "./api/items"; import { parse as parseURL, UrlWithParsedQuery } from "url"; import { ParsedUrlQuery } from "querystring"; +import Client from "./api/interface"; export default class Mixer { static valid_urls = ["/", "/oauth"]; - carrefour: CarrefourItems = new CarrefourItems(); + chain: Client[] = [new CarrefourItems()]; constructor(){ - console.log("Mixer Initialised"); + console.log("+ mixer init"); } http_handler(req: IncomingMessage, res: ServerResponse){ @@ -30,15 +31,17 @@ export default class Mixer { // if query if( urlObj.pathname == "/" ){ - let err:Error = Mixer.query(req, res); + 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()}`})) } + return; + // if oauth } else { - let err:Error = Mixer.oauth(req, res); + 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()}`})) @@ -49,16 +52,24 @@ export default class Mixer { } - static query(req: IncomingMessage, res: ServerResponse) : Error{ + query(req: IncomingMessage, res: ServerResponse) : Error{ let query: ParsedUrlQuery = parseURL(req.url,true).query - console.log('query is:', query['q']) + + 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; } - static oauth(req: IncomingMessage, res: ServerResponse) : Error{ + oauth(req: IncomingMessage, res: ServerResponse) : Error{ console.log(`oauth(${req},${res})`); let query: ParsedUrlQuery = parseURL(req.url,true).query console.log('query is:', query); diff --git a/tsconfig.json b/tsconfig.json index 35c93cb..9a51ec9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,13 +3,16 @@ "baseUrl": ".", "paths": { "*": ["types/*"] }, "module": "commonjs", - "noImplicitAny": true, + // "noImplicitAny": true, "removeComments": true, "moduleResolution": "node", "target": "es6", - "outDir": "dist" + "outDir": "dist", }, "include": [ "src/**/*" + ], + "exclude": [ + "node_modules/**/*" ] } \ No newline at end of file