POST to GET only | accept: application/json but HTML by default

This commit is contained in:
xdrm-brackets 2018-11-12 12:50:12 +01:00
parent d30c445868
commit a43611f664
3 changed files with 70 additions and 6 deletions

3
.gitignore vendored
View File

@ -1,4 +1,5 @@
/node_modules
/package-lock.json
/dist
*.js
*.js
types/request\.d\.ts

6
cnf/api_keys.json Normal file
View File

@ -0,0 +1,6 @@
{
"carrefour": {
"app_id": "1e70cf82-6062-4067-8b6c-e5f34c0643b7",
"app_secret": "eO8cF7qL5hX2wG0bT5hY6aV2kM7oE8aT2hT4iE8iP5aK3aT4pH"
}
}

View File

@ -27,18 +27,28 @@ export default class Mixer {
async http_handler(req: IncomingMessage, res: ServerResponse){
let urlObj : UrlWithParsedQuery = parseURL(req.url,true)
printf('\n -- new client --\n')
let urlObj : UrlWithParsedQuery = parseURL(req.url, true)
// reject invalid requests
if( req.method != 'POST' ) return Mixer.http_error(res, 'only POST method allowed');
if( req.method != 'GET' ) return Mixer.http_error(res, 'only GET method allowed');
else if( Mixer.valid_urls.indexOf(urlObj.pathname) < 0 ) return Mixer.http_error(res, `only URI [${Mixer.valid_urls}] allowed`);
printf('\n -- new request --\n')
try{
let query_result = await this.query(req, res)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify( this.format(query_result) ));
// if accept is set to HTML -> html format
if( req.headers['accept'] && req.headers['accept'].includes("json") ){
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify( this.format(query_result) ));
// fallback to JSON by default
} else{
res.writeHead(200, { 'Content-Type': 'text/html' })
let query = parseURL(req.url,true).query['q']
res.end(this.toHTML(query, this.format(query_result)) );
}
}catch(err){
@ -47,6 +57,8 @@ export default class Mixer {
}
printf(' -- response sent --\n')
}
@ -95,4 +107,49 @@ export default class Mixer {
}
}
toHTML(request:any, input:any) : string {
let html = `<html>
<head>
<title>results of '${request}'</title>
<meta charset='utf8'/>
<style type='text/css'>
table{ border-collapse: collapse; }
td{ border: 1px solid #ccc; text-align: center; padding: 0.2em 1em; }
thead * { font-weight: bold }
</style>
</head>
<body>
<table>
<thead><tr>
<td>name</td>
<td>gtin</td>
<td>description</td>
<td>quantity</td>
<td>images</td>
</tr></thead>
<tbody>`
for( let i = 0 ; i < input.results.length ; i++ ){
html += `<tr>
<td>${input.results[i].name}</td>
<td>${input.results[i].gtin}</td>
<td>${input.results[i].description}</td>
<td><b>${input.results[i].quantity.value}</b> ${input.results[i].quantity.unit}</td><td>`
if( input.results[i]['images'] ){
let keys = Object.keys(input.results[i].images)
for( let k of keys )
if( input.results[i].images[k] != null )
html += `<a href='${input.results[i].images[k]}'><img src='${input.results[i].images[k]}' width=20 height=20/></a>`
}
html += `</td></tr>`
}
return html
}
}