works with Carrefour.Items api

This commit is contained in:
Adrien Marquès 2018-10-23 20:59:33 +02:00
parent 225735a841
commit 9b7e1f6e67
6 changed files with 107 additions and 36 deletions

View File

@ -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": {

View File

@ -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<object|Error>;
call(query: object|string) : Promise<object>;
}
// Defines HTTP methods subset
export enum HTTP_METHOD {
GET,
POST,
PUT,
DELETE
}
export class Parameters{
get: object;
post: object;
constructor(){ this.get = {}; this.post = {}; }
}

79
src/api/items.ts Normal file
View File

@ -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<object>{
// check query
if( typeof query != 'string' )
return new Promise<object>((_,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<object>( (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();
});
}
}

View File

@ -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) => {

View File

@ -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);

View File

@ -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/**/*"
]
}