|
| 1 | +import ProgressBar from 'progress'; |
| 2 | +import config from '../config'; |
| 3 | +import emissionsCoef from '../data/emissions/coefficients.json'; |
| 4 | +import { PoolClient } from 'pg'; |
| 5 | + |
| 6 | +async function run(): Promise<void> { |
| 7 | + const pool = await config.pg(); |
| 8 | + |
| 9 | + const client = await pool.connect(); |
| 10 | + |
| 11 | + const progressBar = new ProgressBar( |
| 12 | + '-> loading [:bar] :percent (:etas remaining)', |
| 13 | + { |
| 14 | + width: 40, |
| 15 | + complete: '=', |
| 16 | + incomplete: ' ', |
| 17 | + renderThrottle: 500, |
| 18 | + total: Object.keys(emissionsCoef).length, |
| 19 | + } |
| 20 | + ); |
| 21 | + |
| 22 | + // For each coefficient in the JSON file, update the corresponding products. |
| 23 | + config.logger.info('Updating product emissions'); |
| 24 | + |
| 25 | + for (const [key, coefficient] of Object.entries(emissionsCoef)) { |
| 26 | + const [_, skuId, region] = key.split('_'); |
| 27 | + await updateProductEmissions(client, skuId, region, coefficient); |
| 28 | + progressBar.tick(); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const updateProductEmissions = async ( |
| 33 | + client: PoolClient, |
| 34 | + skuId: string, |
| 35 | + region: string, |
| 36 | + coefficient: number |
| 37 | +): Promise<void> => { |
| 38 | + const emissionData = JSON.stringify([ |
| 39 | + { |
| 40 | + emissionHash: 'emissionHash', |
| 41 | + unit: 'kgCO2e', |
| 42 | + emissions: coefficient, |
| 43 | + startUsageAmount: 0, |
| 44 | + }, |
| 45 | + ]); |
| 46 | + |
| 47 | + await client.query( |
| 48 | + ` |
| 49 | + UPDATE "products" |
| 50 | + SET "emissions" = $1 |
| 51 | + WHERE "sku" = $2 AND "region" = $3 |
| 52 | + `, |
| 53 | + [emissionData, skuId, region] |
| 54 | + ); |
| 55 | +}; |
| 56 | + |
| 57 | +config.logger.info('Starting: loading data into DB'); |
| 58 | +run() |
| 59 | + .then(() => { |
| 60 | + config.logger.info('Completed: loading data into DB'); |
| 61 | + process.exit(0); |
| 62 | + }) |
| 63 | + .catch((err) => { |
| 64 | + config.logger.error(err); |
| 65 | + process.exit(1); |
| 66 | + }); |
0 commit comments