@svadmin/elasticsearch 0.0.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,22 +1,48 @@
1
1
  {
2
2
  "name": "@svadmin/elasticsearch",
3
- "version": "0.0.1",
4
- "description": "Placeholder for @svadmin/elasticsearch: the package is published from CI with npm trusted publishing. Install a released version instead.",
3
+ "version": "0.2.2",
4
+ "description": "Elasticsearch & OpenSearch DataProvider for svadmin",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "files": [
8
+ "src/**/*.ts",
9
+ "!src/**/*.test.*",
10
+ "!src/**/*.spec.*"
11
+ ],
12
+ "main": "src/index.ts",
13
+ "types": "src/index.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./src/index.ts",
17
+ "default": "./src/index.ts"
18
+ }
19
+ },
20
+ "peerDependencies": {
21
+ "@svadmin/core": "^0.77.0"
22
+ },
23
+ "keywords": [
24
+ "svadmin",
25
+ "elasticsearch",
26
+ "opensearch",
27
+ "data-provider"
28
+ ],
5
29
  "license": "MIT",
30
+ "author": "zuohuadong",
6
31
  "repository": {
7
32
  "type": "git",
8
33
  "url": "git+https://github.com/vibeunion/svadmin.git",
9
34
  "directory": "packages/elasticsearch"
10
35
  },
11
- "homepage": "https://github.com/vibeunion/svadmin/tree/main/packages/elasticsearch#readme",
36
+ "homepage": "https://github.com/vibeunion/svadmin#readme",
12
37
  "bugs": {
13
38
  "url": "https://github.com/vibeunion/svadmin/issues"
14
39
  },
15
- "publishConfig": {
16
- "access": "public"
17
- },
18
- "files": [
19
- "package.json",
20
- "README.md"
21
- ]
40
+ "svadmin": {
41
+ "capabilities": [
42
+ "data"
43
+ ],
44
+ "core": "^0.55.0",
45
+ "stability": "stable",
46
+ "migration": null
47
+ }
22
48
  }
@@ -0,0 +1,254 @@
1
+ import type {
2
+ DataProvider,
3
+ GetListParams,
4
+ GetListResult,
5
+ GetOneParams,
6
+ GetOneResult,
7
+ GetManyParams,
8
+ GetManyResult,
9
+ CreateParams,
10
+ CreateResult,
11
+ UpdateParams,
12
+ UpdateResult,
13
+ DeleteParams,
14
+ DeleteResult,
15
+ BaseRecord,
16
+ Filter,
17
+ } from '@svadmin/core';
18
+
19
+ export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
20
+
21
+ export interface ElasticsearchOptions {
22
+ node: string;
23
+ apiKey?: string;
24
+ username?: string;
25
+ password?: string;
26
+ headers?: Record<string, string>;
27
+ indexMap?: Record<string, string>;
28
+ fetch?: FetchLike;
29
+ }
30
+
31
+ function buildQuery(filters?: Filter[]): Record<string, unknown> {
32
+ if (!filters || filters.length === 0) {
33
+ return { match_all: {} };
34
+ }
35
+
36
+ const must: Record<string, unknown>[] = [];
37
+ const mustNot: Record<string, unknown>[] = [];
38
+ const should: Record<string, unknown>[] = [];
39
+
40
+ for (const filter of filters) {
41
+ if ('field' in filter) {
42
+ const field = filter.field;
43
+ const op = filter.operator;
44
+ const value = filter.value;
45
+
46
+ switch (op) {
47
+ case 'eq':
48
+ must.push({ term: { [field]: value } });
49
+ break;
50
+ case 'ne':
51
+ mustNot.push({ term: { [field]: value } });
52
+ break;
53
+ case 'contains':
54
+ must.push({ match_phrase: { [field]: value } });
55
+ break;
56
+ case 'gte':
57
+ case 'gt':
58
+ case 'lte':
59
+ case 'lt':
60
+ must.push({ range: { [field]: { [op]: value } } });
61
+ break;
62
+ case 'in':
63
+ must.push({ terms: { [field]: Array.isArray(value) ? value : [value] } });
64
+ break;
65
+ default:
66
+ must.push({ match: { [field]: value } });
67
+ }
68
+ } else {
69
+ const nested = filter.value.map((child) => buildQuery([child]));
70
+ if (filter.operator === 'or') should.push(...nested);
71
+ else must.push(...nested);
72
+ }
73
+ }
74
+
75
+ const boolQuery: Record<string, unknown> = {};
76
+ if (must.length > 0) boolQuery['must'] = must;
77
+ if (mustNot.length > 0) boolQuery['must_not'] = mustNot;
78
+ if (should.length > 0) {
79
+ boolQuery['should'] = should;
80
+ boolQuery['minimum_should_match'] = 1;
81
+ }
82
+
83
+ return Object.keys(boolQuery).length > 0 ? { bool: boolQuery } : { match_all: {} };
84
+ }
85
+
86
+ export function createElasticsearchDataProvider(options: ElasticsearchOptions): DataProvider {
87
+ const nodeUrl = options.node.replace(/\/+$/, '');
88
+ const customFetch = options.fetch ?? fetch;
89
+
90
+ function getHeaders(): Record<string, string> {
91
+ const headers: Record<string, string> = {
92
+ 'Content-Type': 'application/json',
93
+ ...(options.headers ?? {}),
94
+ };
95
+ if (options.apiKey) {
96
+ headers['Authorization'] = `ApiKey ${options.apiKey}`;
97
+ } else if (options.username && options.password) {
98
+ const creds = btoa(`${options.username}:${options.password}`);
99
+ headers['Authorization'] = `Basic ${creds}`;
100
+ }
101
+ return headers;
102
+ }
103
+
104
+ function resolveIndex(resource: string): string {
105
+ return options.indexMap?.[resource] ?? resource;
106
+ }
107
+
108
+ function withId<TData extends BaseRecord>(id: string | number, source: Record<string, unknown> = {}): TData {
109
+ return { id, ...source } as unknown as TData;
110
+ }
111
+
112
+ function variablesRecord(value: unknown): Record<string, unknown> {
113
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
114
+ ? value as Record<string, unknown>
115
+ : {};
116
+ }
117
+
118
+ return {
119
+ getApiUrl: () => nodeUrl,
120
+ async getList<TData extends BaseRecord = BaseRecord>(params: GetListParams): Promise<GetListResult<TData>> {
121
+ const index = resolveIndex(params.resource);
122
+ const page = params.pagination?.current ?? 1;
123
+ const size = params.pagination?.pageSize ?? 10;
124
+ const from = (page - 1) * size;
125
+
126
+ const body: Record<string, unknown> = {
127
+ from,
128
+ size,
129
+ query: buildQuery(params.filters),
130
+ };
131
+
132
+ if (params.sorters && params.sorters.length > 0) {
133
+ body['sort'] = params.sorters.map((s) => ({
134
+ [s.field]: { order: s.order.toLowerCase() },
135
+ }));
136
+ }
137
+
138
+ const res = await customFetch(`${nodeUrl}/${index}/_search`, {
139
+ method: 'POST',
140
+ headers: getHeaders(),
141
+ body: JSON.stringify(body),
142
+ });
143
+
144
+ if (!res.ok) {
145
+ throw new Error(`Elasticsearch error: ${res.status} ${res.statusText}`);
146
+ }
147
+
148
+ const json = await res.json() as {
149
+ hits: {
150
+ total: number | { value: number };
151
+ hits: Array<{ _id: string; _source: Record<string, unknown> }>;
152
+ };
153
+ };
154
+
155
+ const total = typeof json.hits.total === 'number' ? json.hits.total : (json.hits.total?.value ?? 0);
156
+ const data = json.hits.hits.map((hit) => withId<TData>(hit._id, hit._source));
157
+
158
+ return { data, total };
159
+ },
160
+
161
+ async getOne<TData extends BaseRecord = BaseRecord>(params: GetOneParams): Promise<GetOneResult<TData>> {
162
+ const index = resolveIndex(params.resource);
163
+ const res = await customFetch(`${nodeUrl}/${index}/_doc/${params.id}`, {
164
+ method: 'GET',
165
+ headers: getHeaders(),
166
+ });
167
+
168
+ if (!res.ok) {
169
+ throw new Error(`Elasticsearch document not found: ${params.id}`);
170
+ }
171
+
172
+ const json = await res.json() as { _id: string; _source: Record<string, unknown> };
173
+ const data = withId<TData>(json._id, json._source);
174
+
175
+ return { data };
176
+ },
177
+
178
+ async getMany<TData extends BaseRecord = BaseRecord>(params: GetManyParams): Promise<GetManyResult<TData>> {
179
+ const index = resolveIndex(params.resource);
180
+ const res = await customFetch(`${nodeUrl}/${index}/_mget`, {
181
+ method: 'POST',
182
+ headers: getHeaders(),
183
+ body: JSON.stringify({ ids: params.ids }),
184
+ });
185
+
186
+ if (!res.ok) {
187
+ throw new Error(`Elasticsearch _mget error: ${res.status}`);
188
+ }
189
+
190
+ const json = await res.json() as {
191
+ docs: Array<{ _id: string; found: boolean; _source?: Record<string, unknown> }>;
192
+ };
193
+
194
+ const data = json.docs
195
+ .filter((doc) => doc.found && doc._source)
196
+ .map((doc) => withId<TData>(doc._id, doc._source));
197
+
198
+ return { data };
199
+ },
200
+
201
+ async create<TData extends BaseRecord = BaseRecord, TVariables = Record<string, unknown>>(
202
+ params: CreateParams<TVariables>,
203
+ ): Promise<CreateResult<TData>> {
204
+ const index = resolveIndex(params.resource);
205
+ const res = await customFetch(`${nodeUrl}/${index}/_doc`, {
206
+ method: 'POST',
207
+ headers: getHeaders(),
208
+ body: JSON.stringify(variablesRecord(params.variables)),
209
+ });
210
+
211
+ if (!res.ok) {
212
+ throw new Error(`Elasticsearch create error: ${res.status}`);
213
+ }
214
+
215
+ const json = await res.json() as { _id: string };
216
+ const data = withId<TData>(json._id, variablesRecord(params.variables));
217
+
218
+ return { data };
219
+ },
220
+
221
+ async update<TData extends BaseRecord = BaseRecord, TVariables = Record<string, unknown>>(
222
+ params: UpdateParams<TVariables>,
223
+ ): Promise<UpdateResult<TData>> {
224
+ const index = resolveIndex(params.resource);
225
+ const res = await customFetch(`${nodeUrl}/${index}/_update/${params.id}`, {
226
+ method: 'POST',
227
+ headers: getHeaders(),
228
+ body: JSON.stringify({ doc: variablesRecord(params.variables) }),
229
+ });
230
+
231
+ if (!res.ok) {
232
+ throw new Error(`Elasticsearch update error: ${res.status}`);
233
+ }
234
+
235
+ const data = withId<TData>(params.id, variablesRecord(params.variables));
236
+ return { data };
237
+ },
238
+
239
+ async deleteOne<TData extends BaseRecord = BaseRecord>(params: DeleteParams): Promise<DeleteResult<TData>> {
240
+ const index = resolveIndex(params.resource);
241
+ const res = await customFetch(`${nodeUrl}/${index}/_doc/${params.id}`, {
242
+ method: 'DELETE',
243
+ headers: getHeaders(),
244
+ });
245
+
246
+ if (!res.ok) {
247
+ throw new Error(`Elasticsearch delete error: ${res.status}`);
248
+ }
249
+
250
+ const data = withId<TData>(params.id);
251
+ return { data };
252
+ },
253
+ };
254
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { createElasticsearchDataProvider } from './elasticsearch-data-provider';
2
+ export type { ElasticsearchOptions, FetchLike } from './elasticsearch-data-provider';
package/README.md DELETED
@@ -1,6 +0,0 @@
1
- # @svadmin/elasticsearch
2
-
3
- This version is a placeholder published only to register the package name and
4
- enable npm trusted publishing from CI. It contains no source code.
5
-
6
- Install a released version (`>= 0.2.1`) instead.