Commit d1246d9b by Иван Кубота

push

parent 6c476a4b
Pipeline #558 canceled with stage
...@@ -48,7 +48,7 @@ router.get('/api', async function(req, res) { ...@@ -48,7 +48,7 @@ router.get('/api', async function(req, res) {
router.all('/', function(req, res) { router.all('/', function(req, res) {
res.end('Open /api for details'); res.end(print(JSON.stringify(data)));
}); });
app.use(function(req, res, next) { app.use(function(req, res, next) {
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -52,6 +52,16 @@ ...@@ -52,6 +52,16 @@
<link type="text/css" rel="stylesheet" href="main.css"> <link type="text/css" rel="stylesheet" href="main.css">
</head> </head>
<body> <body>
<script>initDataProvider($DATA$);init();</script> <script>
let fn = async ()=>{
let response = await fetch( "/api/database/get" );
let message = await response.text();
let data = JSON.parse( message );
initDataProvider(data);init();
};
fn();
</script>
</body> </body>
</html> </html>
\ No newline at end of file
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
"dotenv": "^8.2.0", "dotenv": "^8.2.0",
"express": "^4.17.1", "express": "^4.17.1",
"node-async-router": "^0.0.2", "node-async-router": "^0.0.2",
"request": "^2.88.2",
"yargs": "^15.1.0" "yargs": "^15.1.0"
}, },
"scripts": { "scripts": {
......
const useSubSub = true; const useSubSub = true;
const dataProvider = { let dataProvider = {
maxConnection: 0, maxConnection: 0,
maxTagID: 0, maxTagID: 0,
slice: {}, slice: {},
...@@ -10,10 +10,23 @@ const dataProvider = { ...@@ -10,10 +10,23 @@ const dataProvider = {
}, },
dP = dataProvider, dP = dataProvider,
initDataProvider = function(data) { initDataProvider = function(data) {
Object.assign(dataProvider, {
maxConnection: 0,
maxTagID: 0,
slice: dataProvider.slice,
standardQuestions: {},
tags: [],
connections: {},
products: {}
})
dP = dataProvider;
Object.assign(dP, data); Object.assign(dP, data);
let key; let key;
for(key in data.products){ for(key in data.products){
data.products[key] = new dP.Product.ctor(data.products[key]) data.products[key] = new dP.Product.ctor(data.products[key])
} }
......
...@@ -102,7 +102,7 @@ ...@@ -102,7 +102,7 @@
tr: null, tr: null,
Text: function( val ){ return document.createTextNode( val );} Text: function( val ){ return document.createTextNode( val );}
}; };
'div,span,input,label,canvas,span,textarea,table,tr,td,th,tBody,tHead'.split( ',' ).forEach( function( name ){ 'div,span,input,img,label,canvas,span,textarea,table,tr,td,th,tBody,tHead'.split( ',' ).forEach( function( name ){
D[ name ] = function(){ D[ name ] = function(){
return domEl.apply( null, [ name ].concat([].slice.call(arguments))) return domEl.apply( null, [ name ].concat([].slice.call(arguments)))
}; };
......
...@@ -115,6 +115,10 @@ view.page.Products = function() { ...@@ -115,6 +115,10 @@ view.page.Products = function() {
attr: { title: 'Скрыть', 'data-action': 'hide:' + item.id }, attr: { title: 'Скрыть', 'data-action': 'hide:' + item.id },
on: { click: tableAction } on: { click: tableAction }
}, '←' ), }, '←' ),
item.image && (D.img({attr:{src: item.image, height: '60px'}})),
span( { span( {
cls: 'product-title', cls: 'product-title',
on: { click: tableAction }, on: { click: tableAction },
...@@ -123,8 +127,8 @@ view.page.Products = function() { ...@@ -123,8 +127,8 @@ view.page.Products = function() {
}, me.highlight( item.title ),' ≡' ), }, me.highlight( item.title ),' ≡' ),
( item.tags || [] ).map( t => me.highlight( dP.tagsHash[ t ].name ) ).map( view.cmp.Tag ),
( item.tags || [] ).map( t => me.highlight( dP.tagsHash[ t ].name ) ).map( view.cmp.Tag ),
bonus.full && D.html( { cls: 'product-description' }, textFormat(item.description, true) ), bonus.full && D.html( { cls: 'product-description' }, textFormat(item.description, true) ),
div( div(
......
...@@ -31,23 +31,115 @@ var js = sources.map(a=>path.join(__dirname,'../../public',a)).map(n=>fs.readFil ...@@ -31,23 +31,115 @@ var js = sources.map(a=>path.join(__dirname,'../../public',a)).map(n=>fs.readFil
const data = require("../../db.js"); const data = require("../../db.js");
const body = 'const window = {}, localStorage = {getItem:()=>"{}"};'+js+'; return {quizGenerator, standardGenerator, initDataProvider, seeded: Math.random.seeded, rand}'; const body = 'const window = {}, localStorage = {getItem:()=>"{}"};'+js+'; return {quizGenerator, standardGenerator, initDataProvider, seeded: Math.random.seeded, rand, dP}';
var ctxCtor = new Function('',body);
var ctx = new Function('',body)();
const rand = ctx.rand, var ctx;
seeded = ctx.seeded; var initCtx = function() {
ctx = ctxCtor();
data.after = function(inComeData, skipInit){ ctx.ready = new Promise((r,j)=>{
if( inComeData ){ ctx._r = r;
});
ctx.setData = function(data) {
ctx.initDataProvider( data ); ctx.initDataProvider( data );
countStdQ = Object.values(data.standardQuestions).length; countStdQ = Object.values(data.standardQuestions).length;
//console.log(ctx.dP)
ctx._r();
};
};
const normalizeText = function(text) {
return (text+'').trim().toLowerCase().replace(/[^а-я]/g,'').replace(/[аоуеэюёиыя]+/g,'о')
};
initCtx();
let standardQuestions;
let subcats = {};
data.after = function(inComeData, skipInit){
if( inComeData ){
for(let i in inComeData.products){
let cmp = inComeData.products[i];
subcats[ normalizeText( cmp.title ) ] = cmp.subcat;
}
//ctx.setData(inComeData);
standardQuestions = inComeData.standardQuestions;
firstRequest();
} }
}; };
let theData;
let countStdQ; let countStdQ;
let firstRequest;
module.exports = { module.exports = {
'/api/database/get': {
method: 'GET',
summary: 'Return the database',
options: {},
fn: async function(){
await ctx.ready;
return theData;
}
},
'/api/database/update': {
method: 'GET',
summary: 'Reload data from https://api.new.local.vkusvill.testin.ru/api/admin/category/',
options: {},
fn: firstRequest = async function() {
var request = function(o, fn){fn(false, {body:JSON.stringify(require('../../data/mocked.json'))})};//require('request');
var options = {
'method': 'GET',
'url': 'https://api.new.local.vkusvill.testin.ru/api/admin/category/',
'headers': {}
};
request(options, function (error, response) {
if (error) throw new Error(error);
var s = data,
l = JSON.parse(response.body);
var mimicri = {
tags: [],
connections: [],
products: {},
components: {}
};
var cmpID = 1;
l.forEach(category=>{
if(category.type === 1 && !category.hidden){
category.cards.forEach(card=>{
card.components.forEach(cmp=>{
mimicri.components[cmpID++] = {
id: card.id,
iID: cmp.id,
name: cmp.name
};
});
mimicri.products[card.id] = {
"category_id": card.category_id,
"id": card.id,
"title": card.name,
"description": card.text,
"subcat": subcats[ normalizeText( card.name ) ],
"use": card.is_test,
"image": card.image === null ? void 0 : card.image,
"type": card.type,
"items": card.components.map(a=>a.id)
};
})
}
});
mimicri.standardQuestions = standardQuestions
//console.log(response.body);
initCtx();
theData = JSON.stringify(mimicri);
ctx.setData(mimicri);
});
return 'true';
}
},
'/api/generate/random': { '/api/generate/random': {
method: 'GET', method: 'GET',
summary: 'Generate random quiz', summary: 'Generate random quiz',
...@@ -59,6 +151,7 @@ module.exports = { ...@@ -59,6 +151,7 @@ module.exports = {
exclude: {required: false, description: 'remove human readable log', type: Array} exclude: {required: false, description: 'remove human readable log', type: Array}
}, },
fn: async function(args) { fn: async function(args) {
await ctx.ready; const rand = ctx.rand, seeded = ctx.seeded;
let seed = args.seed || Math.random().toString(36).substr(2); let seed = args.seed || Math.random().toString(36).substr(2);
ctx.seeded.setStringSeed( seed ); ctx.seeded.setStringSeed( seed );
...@@ -103,6 +196,8 @@ module.exports = { ...@@ -103,6 +196,8 @@ module.exports = {
human: {required: false, description: 'aggregate stats and explain questions', type: Boolean} human: {required: false, description: 'aggregate stats and explain questions', type: Boolean}
}, },
fn: async function(args, req, res) { fn: async function(args, req, res) {
await ctx.ready; const rand = ctx.rand, seeded = ctx.seeded;
let seed = args.seed || Math.random().toString(36).substr(2); let seed = args.seed || Math.random().toString(36).substr(2);
ctx.seeded.setStringSeed( seed ); ctx.seeded.setStringSeed( seed );
let used = {}, generated = 0; let used = {}, generated = 0;
...@@ -150,6 +245,8 @@ module.exports = { ...@@ -150,6 +245,8 @@ module.exports = {
break; break;
counter++; counter++;
}while(counter < 100); }while(counter < 100);
debugger
result = ctx.standardGenerator(()=>r); result = ctx.standardGenerator(()=>r);
if(result) if(result)
if(!result){ if(!result){
...@@ -160,8 +257,7 @@ module.exports = { ...@@ -160,8 +257,7 @@ module.exports = {
tries++; tries++;
if(tries === 100) if(tries === 100)
break; break;
}while(result.categoryId+'.'+result.productId in used || (cur.c>1 && result.categoryId === cur.c));
}while(result.categoryId === last.c || result.categoryId+'.'+result.productId in used);
if(tries !== 100){ if(tries !== 100){
cur.c = result.categoryId; cur.c = result.categoryId;
......
...@@ -170,7 +170,7 @@ ${opt.required?'<span class="api-option-required">Required</span>': '<span class ...@@ -170,7 +170,7 @@ ${opt.required?'<span class="api-option-required">Required</span>': '<span class
let result = await api.fn(args, req, res); let result = await api.fn(args, req, res);
// fs.writeFileSync('./data/tmp/full.json', JSON.stringify(data, null, 2)) // fs.writeFileSync('./data/tmp/full.json', JSON.stringify(data, null, 2))
logStream.write(`${humanDate(new Date())} ${api.method}: ${key} ${JSON.stringify(args)}`) logStream.write(`${humanDate(new Date())} ${api.method}: ${key} ${JSON.stringify(args)}`)
logStream.write(`${JSON.stringify(result.log, null,1)}\n`); //logStream.write(`${JSON.stringify(result.log, null,1)}\n`);
res.end(typeof result === 'string' ? result : JSON.stringify(result, null,1), 'utf-8'); res.end(typeof result === 'string' ? result : JSON.stringify(result, null,1), 'utf-8');
clearTimeout(timeout) clearTimeout(timeout)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment