/
redis.ts
332 lines (307 loc) · 8.78 KB
/
redis.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* eslint-disable @typescript-eslint/no-unused-vars */
let redis: any;
try {
redis = require('ioredis');
} catch (error: any) {
//
}
export interface AdapterSettingsRedis {
host?: string;
port?: number;
database: string;
}
import stream from 'stream';
import _ from 'lodash';
import { Connection } from '../connection';
import { ColumnPropertyInternal } from '../model';
import { Transaction } from '../transaction';
import * as types from '../types';
import { tableize } from '../util/inflector';
import {
AdapterBase,
AdapterCountOptions,
AdapterDeleteOptions,
AdapterFindOptions,
AdapterUpsertOptions,
} from './base';
// Adapter for Redis
// @namespace adapter
export class RedisAdapter extends AdapterBase {
/** @internal */
public support_upsert = false;
/** @internal */
public key_type: any = types.Integer;
/** @internal */
private _client: any;
// Creates a Redis adapter
/** @internal */
constructor(connection: Connection) {
super();
this._connection = connection;
}
/** @internal */
public async drop(model_name: string) {
await this.delete(model_name, [], { orders: [] });
}
/** @internal */
public valueToDB(value: any, column: any, property: any) {
if (value == null) {
return;
}
switch (property.type_class) {
case types.Number:
case types.Integer:
return value.toString();
case types.Date:
return new Date(value).getTime().toString();
case types.Boolean:
if (value) {
return '1';
} else {
return '0';
}
break;
case types.Object:
return JSON.stringify(value);
default:
return value;
}
}
/** @internal */
public async create(
model_name: string,
data: any,
options: { transaction?: Transaction; use_id_in_data?: boolean },
): Promise<any> {
data.$_$ = ''; // ensure that there is one argument(one field) at least
let id;
try {
if (options.use_id_in_data) {
id = data.id;
} else {
id = await this._client.incr(`${tableize(model_name)}:_lastid`);
}
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
try {
await this._client.hmset(`${tableize(model_name)}:${id}`, data);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
return id;
}
/** @internal */
public async createBulk(
model_name: string,
data: any[],
options: { transaction?: Transaction; use_id_in_data?: boolean },
): Promise<any[]> {
return await this._createBulkDefault(model_name, data, options);
}
/** @internal */
public async update(model_name: string, data: any, options: { transaction?: Transaction }) {
const key = `${tableize(model_name)}:${data.id}`;
delete data.id;
data.$_$ = ''; // ensure that there is one argument(one field) at least
let exists;
try {
exists = await this._client.exists(key);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
if (!exists) {
return;
}
try {
await this._client.del(key);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
try {
await this._client.hmset(key, data);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
}
/** @internal */
public async updatePartial(
model_name: string,
data: any,
conditions: Array<Record<string, any>>,
options: { transaction?: Transaction },
): Promise<number> {
const fields_to_del = Object.keys(data).filter((key) => data[key] == null);
fields_to_del.forEach((key) => {
return delete data[key];
});
fields_to_del.push('$_$'); // ensure that there is one argument at least
const table = tableize(model_name);
data.$_$ = ''; // ensure that there is one argument(one field) at least
const keys = await this._getKeys(table, conditions);
for (const key of keys) {
const args = _.clone(fields_to_del);
args.unshift(key);
try {
await this._client.hdel(args);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
try {
await this._client.hmset(key, data);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
}
return keys.length;
}
/** @internal */
public async upsert(
model_name: string,
data: any,
conditions: Array<Record<string, any>>,
options: AdapterUpsertOptions,
): Promise<void> {
return Promise.reject(new Error('not implemented'));
}
/** @internal */
public async findById(
model_name: string,
id: any,
options: { select?: string[]; explain?: boolean; transaction?: Transaction },
): Promise<any> {
let result;
try {
const key = `${tableize(model_name)}:${id}`;
if (await this._client.exists(key)) {
result = await this._client.hgetall(key);
}
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
if (result) {
result.id = id;
return this._convertToModelInstance(model_name, result, options);
} else {
throw new Error('not found');
}
}
/** @internal */
public async find(
model_name: string,
conditions: Array<Record<string, any>>,
options: AdapterFindOptions,
): Promise<any> {
const table = tableize(model_name);
const keys = await this._getKeys(table, conditions);
let records: any[] = await Promise.all(
keys.map(async (key: any) => {
const result = (await this._client.exists(key)) ? await this._client.hgetall(key) : undefined;
if (result) {
result.id = Number(key.substr(table.length + 1));
}
return result;
}),
);
records = records.filter((record) => record != null);
return records.map((record) => {
return this._convertToModelInstance(model_name, record, options);
});
}
/** @internal */
public stream(
model_name: string,
conditions: Array<Record<string, any>>,
options: AdapterFindOptions,
): stream.Readable {
throw new Error('not implemented');
}
/** @internal */
public async count(
model_name: string,
conditions: Array<Record<string, any>>,
options: AdapterCountOptions,
): Promise<number> {
return Promise.reject(new Error('not implemented'));
}
/** @internal */
public async delete(
model_name: string,
conditions: Array<Record<string, any>>,
options: AdapterDeleteOptions,
): Promise<number> {
const keys = await this._getKeys(tableize(model_name), conditions);
if (keys.length === 0) {
return 0;
}
let count;
try {
count = await this._client.del(keys);
} catch (error: any) {
throw RedisAdapter.wrapError('unknown error', error);
}
return count;
}
/** @internal */
public close(): void {
//
}
/**
* Connects to the database
* @internal
*/
public async connect(settings: AdapterSettingsRedis) {
const methods = ['del', 'exists', 'hdel', 'hgetall', 'hmset', 'incr', 'keys', 'select'];
this._client = redis.createClient(settings.port || 6379, settings.host || '127.0.0.1');
return await this._client.select(settings.database || 0);
}
/** @internal */
protected valueToModel(value: any, property: ColumnPropertyInternal, query_record_id_as_string: boolean) {
switch (property.type_class) {
case types.Number:
case types.Integer:
return Number(value);
case types.Date:
return new Date(Number(value));
case types.Boolean:
return value !== '0';
case types.Object:
return JSON.parse(value);
default:
if (property.record_id && query_record_id_as_string) {
return String(value);
}
return value;
}
}
/** @internal */
private async _getKeys(table: any, conditions: Array<Record<string, any>> | Record<string, any>) {
if (Array.isArray(conditions)) {
if (conditions.length === 0) {
return await this._client.keys(`${table}:*`);
}
const all_keys: any[] = [];
await Promise.all(
conditions.map(async (condition) => {
const keys = await this._getKeys(table, condition);
[].push.apply(all_keys, keys);
}),
);
return all_keys;
} else if (typeof conditions === 'object' && conditions.id) {
if (conditions.id.$in) {
return conditions.id.$in.map((id: any) => `${table}:${id}`);
} else {
return [`${table}:${conditions.id}`];
}
}
return [];
}
}
export function createAdapter(connection: Connection) {
if (!redis) {
console.log('Install redis module to use this adapter');
process.exit(1);
}
return new RedisAdapter(connection);
}