repEs.js 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
import axios from "axios";


class RepEs {

    constructor(config) {
        this.config = config
        this.index_url = config.index_url
        this.index_name = config.index_name
10
        this.token = process.env?.INSCODE_API_KEY??'default'
11 12 13 14
    }

    query (keyword) {

15
        const url = this.index_url + '?user_token=' + this.token + '&index_name=' + this.index_name
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        return new Promise(function(resolve,rejcet){
            axios.get(url,{
                params: {
                    keyword: encodeURI(keyword),
                }
            }).then(res => {

                if (res?.status === 200 && res?.data?.code === 200) {
                    const result = []
                    res?.data?.data?.hits.forEach(element => {
                        result.push({
                            page_content: element?._source?.content
                        })
                    });
                    resolve(result)

                }
                console.info(res)


            }).catch((err) => {
                console.error(err)
                rejcet()
            })
        })
        
    }

44
    add (content) {
45
        const name = '/' + this.index_name
46
        const url = this.index_url + '/' + this.index_name
47
        const token = this.token
48 49 50 51 52 53 54 55

        const instance = axios.create({
            baseURL: this.index_url,
            timeout: 5000,
            withCredentials: true, // 允许跨域请求
          });

          
56
        return new Promise(function(resolve,rejcet){
57
            instance.put(name,
58 59 60 61
                {
                user_token: token,
                content: content,
                }, 
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                  }).then(res => {

                        if (res?.status === 200 && res?.data?.code === 200) {
                            const result = []
                            res?.data?.data?.hits.forEach(element => {
                                result.push({
                                    page_content: element?._source?.content
                                })
                            });
                            resolve(result)

                        }
                        console.info(res)
79 80 81 82 83 84 85 86 87 88


            }).catch((err) => {
                console.error(err)
                rejcet()
            })
        })

    }

89 90 91
}

export default RepEs