|
| 1 | +import axios from 'axios' |
| 2 | +import { createGunzip } from 'node:zlib' |
| 3 | +import Papa from 'papaparse' |
| 4 | +import { redis } from '../../src/adapters/redis/client' |
| 5 | +import { KEYS } from '../../src/adapters/redis/constant' |
| 6 | +import { converIpToNumber } from '../../src/features/geolocation/geolocation.service' |
| 7 | + |
| 8 | +export const exec = async () => { |
| 9 | + try { |
| 10 | + const geoipUrl = process.env.GEOIP_URL |
| 11 | + |
| 12 | + if (!geoipUrl) { |
| 13 | + throw new Error('GEOIP_URL is required') |
| 14 | + } |
| 15 | + |
| 16 | + const today = new Date() |
| 17 | + |
| 18 | + const datasourceStream = ( |
| 19 | + await axios.get( |
| 20 | + geoipUrl.replace( |
| 21 | + '{{YYYY-MM}}', |
| 22 | + `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}` |
| 23 | + ), |
| 24 | + { |
| 25 | + responseType: 'stream', |
| 26 | + } |
| 27 | + ) |
| 28 | + ).data.pipe(createGunzip()) |
| 29 | + |
| 30 | + const parseStream = Papa.parse(Papa.NODE_STREAM_INPUT, { |
| 31 | + header: false, |
| 32 | + }) |
| 33 | + |
| 34 | + datasourceStream.pipe(parseStream) |
| 35 | + |
| 36 | + const sortedArray = [] |
| 37 | + |
| 38 | + for await (const chunk of parseStream) { |
| 39 | + const [ipStart, _, countryCode] = chunk |
| 40 | + |
| 41 | + // Ignore IPv6 addresses |
| 42 | + if (!ipStart.includes('.')) { |
| 43 | + continue |
| 44 | + } |
| 45 | + |
| 46 | + const ipStartNumber = converIpToNumber(ipStart) |
| 47 | + sortedArray.push({ ipStartNum: ipStartNumber, countryCode }) |
| 48 | + } |
| 49 | + |
| 50 | + await redis.set(KEYS.geolocation, JSON.stringify(sortedArray)) |
| 51 | + await redis.persist(KEYS.geolocation) |
| 52 | + console.log(`Stored ${sortedArray.length} IP to redis`) |
| 53 | + } catch (err) { |
| 54 | + console.error('Geolocation error', err) |
| 55 | + throw err |
| 56 | + } |
| 57 | +} |
0 commit comments