I've encountered a strange issue. When I use console.log(self
) to log the variable, it shows that the output key is set and contains all the values. However, if I try to log console.log(self.output)
, it returns undefined. Does anyone know why this is happening?
Below is my code snippet:
interface SearchOutput {
total: 0,
per_page: number,
current_page: number,
last_page: number,
from: number,
to: number,
data: Array<Object>
}
interface SearchParams {
query: string,
perPage: number,
index: string,
type: string,
page: number
}
export class Elastic {
from: number;
to: number;
client: any;
output: SearchOutput;
error: any;
constructor(host: string, log: string, elasticsearch: any) {
this.client = new elasticsearch.Client({
host: host,
log: log
})
}
public search({query, perPage, index, type, page}:SearchParams): SearchOutput {
let self = this;
this.client.search({
'index': index,
'type': type,
'body': {
'query': {
'bool': {
'must': {
'query_string': {
'query': query,
'default_operator': 'AND',
'fuzziness': 1
}
}, 'filter': []
}
}
},
'size': perPage,
'from': 0
},
(err, response) => {
const {hits, hits: {total}} = response
const lastPage = Math.ceil(total / perPage)
const from = (page * perPage) - perPage + 1
const to = (page < lastPage) ? page * perPage : total
let output = {
total: total,
per_page: perPage,
current_page: page,
last_page: lastPage,
from: from,
to: to,
data: []
}
if (total >= 1) {
for (const key in hits.hits) {
if (hits.hits.hasOwnProperty(key)) {
output.data.push(hits.hits[key]._source);
}
}
} else {
output.data = [];
}
self.output = output;
}
);
console.log(self); // outputs Elastic {client: EsApiClient, output:SearchOutput Objest with all values}
console.log(self.output) // outputs undefined
return self.output;
}
}