UNPKG

2.34 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3const assert = require('assert');
4const Redis = require('ioredis').Cluster;
5const { 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 // ensure that this user exists
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 // ensure that referral was not already set
48 if (argv.overwrite !== true) {
49 assert.equal(currentReferral, null, 'referral was already set, pass --overwrite to args to force it');
50 }
51
52 // verify that referral code is valid, which is basically
53 // checking whether that alias exists or not
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); // eslint-disable-line no-console
72 } finally {
73 redis.disconnect();
74 }
75})();