-
Notifications
You must be signed in to change notification settings - Fork 26
/
meilisearch.js
80 lines (65 loc) · 1.85 KB
/
meilisearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const { URL } = require('url');
/**
* @type {import("axios").AxiosInstance}
*/
const axios = require('axios');
/**
* @type {import("../../types.js").IndexerInterface}
*/
module.exports = function meilisearch(config) {
const axiosConfig = {
headers: config.headers || {},
};
if (config.key) {
// Meilisearch changed their authorization in 0.25 from the
// 'X-Meili-API-Key' header to Authorization bearer.
// Include old headers for compatibility with pre-0.25 versions of Meilisearch
axiosConfig.headers['X-Meili-API-Key'] = config.key;
// New auth headers for 0.25+
axiosConfig.headers['Authorization'] = `Bearer ${config.key}`;
}
if (!config.host) {
throw Error('No HOST set. The server.host is mandatory.');
}
const host = new URL(config.host);
if (!host.hostname || (host.pathname && host.pathname !== '/')) {
throw Error(`Invalid server.host, it must be like http://meili.example.com/`);
}
return {
createIndex,
deleteItems,
deleteItem,
updateItem,
};
async function createIndex(collection) {}
async function deleteItems(collection) {
try {
await axios.delete(`${config.host}/indexes/${collection}`, axiosConfig);
} catch (error) {
if (error.response && error.response.status === 404) return;
throw error;
}
}
async function deleteItem(collection, id) {
try {
await axios.delete(`${config.host}/indexes/${collection}/documents/${id}`, axiosConfig);
} catch (error) {
if (error.response && error.response.status === 404) return;
throw error;
}
}
async function updateItem(collection, id, data, pk) {
try {
await axios.post(
`${config.host}/indexes/${collection}/documents?primaryKey=${pk}`,
[{ [pk]: id, ...data }],
axiosConfig
);
} catch (error) {
if (error.response) {
throw { message: error.toString(), response: error.response };
}
throw error;
}
}
};