ask api changes, so it wont search unnecesary question dbs

This commit is contained in:
mrfry 2021-01-09 12:38:18 +01:00
parent 0463ab3cd2
commit b53fd84bf2
5 changed files with 116 additions and 65 deletions

View file

@ -3,6 +3,7 @@ import logger from '../utils/logger'
interface Options { interface Options {
loggableKeywords: Array<string> loggableKeywords: Array<string>
loggableModules: Array<string> loggableModules: Array<string>
exceptions: Array<string>
} }
export default function(options: Options): any { export default function(options: Options): any {

View file

@ -34,6 +34,7 @@ import {
logResult, logResult,
backupData, backupData,
shouldSaveDataFile, shouldSaveDataFile,
shouldSearchDataFile,
loadJSON, loadJSON,
Result, Result,
} from '../../utils/actions' } from '../../utils/actions'
@ -930,10 +931,62 @@ function GetApp(): ModuleType {
} }
}) })
function getNewQdb(location, maxIndex) {
// TODO: should check if location is a not empty string
logger.Log(
`No suitable questiondbs found for ${location}, creating a new one...`
)
const newDb: DataFile = {
path: `${location}.json`,
name: location,
shouldSearch: {
location: {
val: location,
},
},
shouldSave: {
location: {
val: location,
},
},
}
utils.WriteFile(
JSON.stringify(
[
...utils.ReadJSON(dbsFile),
newDb, // stored as 'data.json', but is './publicDirs/.../data.json' runtime
],
null,
2
),
dbsFile
)
// "loading" new db
const loadedNewDb: QuestionDb = {
...newDb,
data: [],
path: publicDir + newDb.path,
index: maxIndex,
}
utils.WriteFile('[]', loadedNewDb.path)
questionDbs.push(loadedNewDb)
// TODO: problem: new dbs wont get to workers before trying to search with them.
msgAllWorker({
newdb: loadedNewDb,
type: 'newdb',
})
return loadedNewDb
}
app.post('/isAdding', function(req: Request, res: any) { app.post('/isAdding', function(req: Request, res: any) {
logger.LogReq(req) logger.LogReq(req)
const user: User = req.session.user const user: User = req.session.user
const dryRun = testUsers.includes(user.id) const dryRun = testUsers.includes(user.id)
const location = req.body.location.split('/')[2]
try { try {
let maxIndex = -1 let maxIndex = -1
@ -945,49 +998,7 @@ function GetApp(): ModuleType {
}, []) }, [])
if (suitedQuestionDbs.length === 0) { if (suitedQuestionDbs.length === 0) {
const location = req.body.location.split('/')[2] suitedQuestionDbs.push(getNewQdb(location, maxIndex))
// TODO: should check if location is a not empty string
logger.Log(
`No suitable questiondbs found for ${location}, creating a new one...`
)
const newDb: DataFile = {
path: `${location}.json`,
name: location,
shouldSave: {
location: {
val: location,
},
},
}
utils.WriteFile(
JSON.stringify(
[
...utils.ReadJSON(dbsFile),
newDb, // stored as 'data.json', but is './publicDirs/.../data.json' runtime
],
null,
2
),
dbsFile
)
// "loading" new db
const loadedNewDb: QuestionDb = {
...newDb,
data: [],
path: publicDir + newDb.path,
index: maxIndex,
}
utils.WriteFile('[]', loadedNewDb.path)
suitedQuestionDbs.push(loadedNewDb)
questionDbs.push(loadedNewDb)
// TODO: problem: new dbs wont get to workers before trying to search with them.
msgAllWorker({
newdb: loadedNewDb,
type: 'newdb',
})
} }
processIncomingRequest(req.body, suitedQuestionDbs, dryRun, user) processIncomingRequest(req.body, suitedQuestionDbs, dryRun, user)
@ -1048,16 +1059,16 @@ function GetApp(): ModuleType {
} }
} }
function saveQuestion(questions, subj, location, userid) { function saveQuestion(questions, subj, testUrl, userid) {
// TODO: clear folder every now and then, check if saved questions exist // TODO: clear folder every now and then, check if saved questions exist
const questionsToSave = { const questionsToSave = {
questions: questions, questions: questions,
subj: subj, subj: subj,
userid: userid, userid: userid,
location: location, testUrl: testUrl,
date: new Date(), date: new Date(),
} }
const fname = `${utils.GetDateString()}_${userid}_${location}.json` const fname = `${utils.GetDateString()}_${userid}_${testUrl}.json`
const subject = getSubjNameWithoutYear(subj) const subject = getSubjNameWithoutYear(subj)
const subjPath = `${savedQuestionsDir}/${subject}` const subjPath = `${savedQuestionsDir}/${subject}`
const savedSubjQuestionsFilePath = `${subjPath}/${savedQuestionsFileName}` const savedSubjQuestionsFilePath = `${subjPath}/${savedQuestionsFileName}`
@ -1072,7 +1083,7 @@ function GetApp(): ModuleType {
fname: fname, fname: fname,
subj: subj, subj: subj,
userid: userid, userid: userid,
location: location, testUrl: testUrl,
date: new Date(), date: new Date(),
}) })
utils.WriteFile(JSON.stringify(savedQuestions), savedSubjQuestionsFilePath) utils.WriteFile(JSON.stringify(savedQuestions), savedSubjQuestionsFilePath)
@ -1094,12 +1105,14 @@ function GetApp(): ModuleType {
return return
} }
const subj: any = req.body.subj || '' const subj: any = req.body.subj || ''
const location = req.body.location.split('/')[2] const testUrl = req.body.testUrl
? req.body.testUrl.split('/')[2]
: undefined
writeAskData(req.body) writeAskData(req.body)
const resultPromises = req.body.questions.map((question) => { const resultPromises = req.body.questions.map((question) => {
return getResult(question, subj, null, req.query) return getResult(question, subj, null, req.body, testUrl)
}) })
Promise.all(resultPromises).then((results) => { Promise.all(resultPromises).then((results) => {
@ -1120,7 +1133,7 @@ function GetApp(): ModuleType {
return acc return acc
}, []) }, [])
saveQuestion(saveableQuestions, subj, location, user.id) saveQuestion(saveableQuestions, subj, testUrl, user.id)
}) })
}) })
@ -1155,18 +1168,33 @@ function GetApp(): ModuleType {
} }
}) })
function getResult(question, subj, recData, recievedData) { function getResult(question, subj, recData, recievedData, testUrl?) {
return new Promise((resolve) => { return new Promise((resolve) => {
let searchIn = testUrl
? questionDbs.reduce((acc, qdb, i) => {
if (shouldSearchDataFile(qdb, testUrl)) {
acc.push(i)
}
return acc
}, [])
: 'all'
if (searchIn.length === 0) {
searchIn = 'all'
}
// searchIn could be [0], [1], ... to search every db in different thread. Put this into a // searchIn could be [0], [1], ... to search every db in different thread. Put this into a
// forEach(qdbs) to achieve this // forEach(qdbs) to achieve this
doALongTask({ doALongTask({
type: 'work', type: 'work',
data: { data: {
searchIn: 'all', searchIn: searchIn,
testUrl: testUrl,
question: question, question: question,
subjName: subj, subjName: subj,
questionData: recData, questionData: recData,
searchInAllIfNoResult: true, searchInAllIfNoResult: true,
searchTillMatchPercent: 30,
}, },
}) })
.then((taskResult) => { .then((taskResult) => {

View file

@ -20,6 +20,13 @@ export interface Subject {
export interface DataFile { export interface DataFile {
path: string path: string
name: string name: string
shouldSearch:
| string
| {
location?: {
val: string
}
}
shouldSave: { shouldSave: {
location?: { location?: {
val: string val: string

View file

@ -263,6 +263,22 @@ function processIncomingRequestUsingDb(
}) })
} }
export function shouldSearchDataFile(df: DataFile, testUrl: string): Boolean {
if (typeof df.shouldSearch === 'string' && df.shouldSearch === 'always') {
return true
}
if (typeof df.shouldSearch === 'object') {
if (df.shouldSearch.location) {
const { val } = df.shouldSearch.location
return testUrl.includes(val)
}
}
// FIXME: always return true if it gets here?
return true
}
export function shouldSaveDataFile( export function shouldSaveDataFile(
df: DataFile, df: DataFile,
recievedData: RecievedData recievedData: RecievedData

View file

@ -315,7 +315,7 @@ function questionToString(question: Question) {
// --------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------
// Subject // Subject
// --------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------
function searchQuestion( function searchSubject(
subj: Subject, subj: Subject,
question: Question, question: Question,
subjName: string, subjName: string,
@ -465,7 +465,7 @@ function doSearch(
.includes(getSubjNameWithoutYear(subj.Name).toLowerCase()) .includes(getSubjNameWithoutYear(subj.Name).toLowerCase())
) { ) {
logger.DebugLog(`Searching in ${subj.Name} `, 'searchworker', 2) logger.DebugLog(`Searching in ${subj.Name} `, 'searchworker', 2)
const subjRes = searchQuestion( const subjRes = searchSubject(
subj, subj,
questionToSearch, questionToSearch,
subjName, subjName,
@ -473,14 +473,13 @@ function doSearch(
) )
result = result.concat(subjRes) result = result.concat(subjRes)
if (searchTillMatchPercent) { if (searchTillMatchPercent) {
// TODO: this should return true to continue searching? return !subjRes.some((sr) => {
return subjRes.every((sr) => { return sr.match >= searchTillMatchPercent
return sr.match <= searchTillMatchPercent
}) })
} }
return true return true
} }
// TODO: data.every should always return something! true or false? return true
}) })
if (searchInAllIfNoResult) { if (searchInAllIfNoResult) {
@ -495,18 +494,19 @@ function doSearch(
1 1
) )
data.every((subj) => { data.every((subj) => {
const subjRes = searchQuestion( const subjRes = searchSubject(
subj, subj,
questionToSearch, questionToSearch,
subjName, subjName,
searchTillMatchPercent searchTillMatchPercent
) )
result = result.concat(subjRes) result = result.concat(subjRes)
if (searchTillMatchPercent) { if (searchTillMatchPercent) {
// TODO: this should return true to continue searching? const continueSearching = !subjRes.some((sr) => {
return subjRes.every((sr) => { return sr.match >= searchTillMatchPercent
return sr.match < searchTillMatchPercent
}) })
return continueSearching
} }
return true return true
}) })
@ -546,11 +546,10 @@ if (!isMainThread) {
questionData, questionData,
searchTillMatchPercent, searchTillMatchPercent,
searchInAllIfNoResult, searchInAllIfNoResult,
searchIn,
index,
} = msg.data } = msg.data
const index = msg.index
const searchIn = msg.data.searchIn
// console.log( // console.log(
// `[THREAD #${workerIndex}]: staring work${ // `[THREAD #${workerIndex}]: staring work${
// !isNaN(index) ? ` on job index #${index}` : '' // !isNaN(index) ? ` on job index #${index}` : ''