1 | #!/usr/bin/env node
|
2 |
|
3 | const assert = require('assert');
|
4 | const Redis = require('ioredis').Cluster;
|
5 | const { argv } = require('yargs')
|
6 | .option('id', {
|
7 | type: 'string',
|
8 | description: 'user id that is being altered',
|
9 | required: true,
|
10 | })
|
11 | .option('code', {
|
12 | type: 'string',
|
13 | description: 'referral code to assign to the user',
|
14 | required: true,
|
15 | })
|
16 | .option('overwrite', {
|
17 | type: 'boolean',
|
18 | description: 'when referral was already set - must pass to overwrite',
|
19 | default: false,
|
20 | });
|
21 |
|
22 | (async () => {
|
23 | const conf = require('../lib/config');
|
24 | const {
|
25 | USERS_REFERRAL_INDEX,
|
26 | USERS_REFERRAL_FIELD,
|
27 | USERS_METADATA,
|
28 | USERS_ALIAS_TO_ID,
|
29 | } = require('../lib/constants');
|
30 |
|
31 | const handleRedisPipelineError = require('../lib/utils/pipeline-error');
|
32 | const redisKey = require('../lib/utils/key');
|
33 | const redisConfig = conf.get('/redis', { env: process.env.NODE_ENV });
|
34 | const audience = conf.get('/jwt/defaultAudience', { env: process.env.NODE_ENV });
|
35 | const opts = { ...redisConfig.options, lazyConnect: true };
|
36 | const redis = new Redis(redisConfig.hosts, opts);
|
37 | const metaKey = redisKey(argv.id, USERS_METADATA, audience);
|
38 |
|
39 | try {
|
40 | await redis.connect();
|
41 |
|
42 |
|
43 | assert.equal(await redis.exists(metaKey), 1, 'user does not exist');
|
44 |
|
45 | const currentReferral = await redis.hget(metaKey, USERS_REFERRAL_FIELD);
|
46 |
|
47 |
|
48 | if (argv.overwrite !== true) {
|
49 | assert.equal(currentReferral, null, 'referral was already set, pass --overwrite to args to force it');
|
50 | }
|
51 |
|
52 |
|
53 |
|
54 | assert.equal(
|
55 | await redis.hexists(USERS_ALIAS_TO_ID, argv.code),
|
56 | 1,
|
57 | 'referral code is invalid - it does not exist'
|
58 | );
|
59 |
|
60 | const commands = [
|
61 | ['hset', metaKey, USERS_REFERRAL_FIELD, `"${argv.code}"`],
|
62 | ['sadd', `${USERS_REFERRAL_INDEX}:${argv.code}`, argv.id],
|
63 | ];
|
64 |
|
65 | if (currentReferral) {
|
66 | commands.push(['srem', `${USERS_REFERRAL_INDEX}:${JSON.parse(currentReferral)}`, argv.id]);
|
67 | }
|
68 |
|
69 | await redis.pipeline(commands).exec().then(handleRedisPipelineError);
|
70 | } catch (e) {
|
71 | console.error('Failed', e);
|
72 | } finally {
|
73 | redis.disconnect();
|
74 | }
|
75 | })();
|