-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (70 loc) · 2.32 KB
/
index.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
const { nanoid } = require('nanoid');
const Redis = require('ioredis');
class TinyLink {
constructor(opts) {
if (!opts.client || !(opts.client instanceof Redis)) {
throw new Error('An ioredis instance must be provided');
}
this.prefix = opts.prefix == null ? "tiny-link:" : opts.prefix
this.redis = opts.client;
this.ttl = opts.ttl || 0
}
async shortenUrl(originalUrl, ttlInSeconds) {
ttlInSeconds = ttlInSeconds || this.ttl || 0;
try {
const identifier = nanoid();
let key = this.prefix + identifier;
if (ttlInSeconds) {
await this.redis.setex(key, ttlInSeconds, originalUrl);
} else {
await this.redis.set(key, originalUrl);
}
return identifier;
}
catch (error) {
throw new Error(`Failed to shorten URL: ${error && error.message}`)
}
}
async getOriginalUrl(identifier) {
try {
let key = this.prefix + identifier;
const originalUrl = await this.redis.get(key);
if (!originalUrl) {
throw new Error(`${identifier} not found`);
}
return originalUrl;
}
catch (error) {
throw new Error(`Failed to get shorten URL: ${error && error.message}`)
}
}
async deleteKey(identifier) {
try {
const key = this.prefix + identifier;
const result = await this.redis.del(key);
return result > 0;
}
catch (error) {
throw new Error(`Failed to delete shorten URL: ${error && error.message}`)
}
}
async flushKeys() {
try {
const keys = await this.redis.keys(`${this.prefix}*`);
if (keys.length === 0) {
return 0;
}
const pipeline = this.redis.pipeline();
keys.forEach((key) => {
pipeline.del(key);
});
const results = await pipeline.exec();
const flushedCount = results.filter(([err, result]) => result === 1).length;
return flushedCount;
}
catch (error) {
throw new Error(`Failed to flush keys ${error && error.message}`)
}
}
}
module.exports = {TinyLink};