const fs=require('fs')
const path=require('path')
const list=fs.readdirSync(__dirname)
const objList=[]
list.forEach(function (name){
if(name.indexOf('api')===0){
const obj=require(path.join(__dirname,name))
if(Object.prototype.toString.call(obj)==='[object Object]'){
objList.push(obj)
}else if(Object.prototype.toString.call(obj)==='[object Array]'){
obj.forEach(function (d){
objList.push(d)
})
}
}
})
const view={
objList:objList,
isInclude(item1,item2){
if(Object.prototype.toString.call(item1)==='[object Object]'&&Object.prototype.toString.call(item2)==='[object Object]'){
let isOk=true
for(let k in item2){
if(!this.isInclude(item1[k],item2[k])){
isOk=false
break
}
}
return isOk
}else{
return item1===item2
}
},
async match(params,objList){
let hasItem
for(let i=0;i<objList.length;i++){
const item=objList[i]
let isMath=false
if(Object.prototype.toString.call(item.match)==='[object Object]'){
if(this.isInclude(params,item.match)){
isMath=true
}
}else if(Object.prototype.toString.call(item.match)==='[object Function]'){
isMath=item.match(params)
}else if(Object.prototype.toString.call(item.match)==='[object AsyncFunction]'){
isMath=await item.match(params)
}
if(isMath){
hasItem=item
break
}
}
return hasItem
},
async getData(params,cacheTime){
let item=await this.match(params,objList)
if(item){
if(Object.prototype.toString.call(item.getData)==='[object Object]'){
return item.getData
}else if(Object.prototype.toString.call(item.getData)==='[object Function]'){
return item.getData(params)
}else if(Object.prototype.toString.call(item.getData)==='[object AsyncFunction]'){
return await item.getData(params)
}
}
},
async test(){
const list=[]
for(let i=0;i<objList.length;i++){
const item=objList[i]
list.push(await this.getData(item.params))
}
return list
}
}
module.exports=view
objList.forEach(function (obj){
obj.super=view
})