Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added script to init district in local environment from production data in main and exploitation DBs #453

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions toolbox.dev/scripts/init-district-cogs-in-db-from-production.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* eslint-disable no-await-in-loop */
import fetch from 'node-fetch'
import {init, District, sequelize} from '../../lib/util/sequelize.js'
import mongo from '../../lib/util/mongo.cjs'

const BAN_API_PRODUCTION_URL = 'https://plateforme.adresse.data.gouv.fr/api'

const main = async () => {
await init()
await mongo.connect()
const cogs = process.argv.slice(2)
for (const cog of cogs) {
try {
const response = await fetch(`${BAN_API_PRODUCTION_URL}/district/cog/${cog}`)
if (!response.ok) {
const message = await response.text()
throw new Error(`Error while fetching district cog ${cog} : ${message}`)
}

const district = (await response.json())?.response?.[0]
const formattedDistrictForMainDB = formatDistrictForMainDB(district)
const districtID = formattedDistrictForMainDB.id
console.log(`District id ${districtID} (cog : ${cog}) fetched from production API`)
await District.bulkCreate([formattedDistrictForMainDB], {updateOnDuplicate: ['id']})
console.log(`District ${districtID} (cog : ${cog}) created or updated in local main database (postgresql)`)
const formattedDistrictForExploitationDB = formatDistrictForExploitationDB(district)
await mongo.db.collection('communes').updateOne({codeCommune: cog}, {$set: formattedDistrictForExploitationDB}, {upsert: true})
console.log(`District ${districtID} (cog : ${cog}) created or updated in local exploitation database (mongodb)`)
} catch (error) {
console.error(error)
}
}

await mongo.disconnect()
await sequelize.close()
}

const formatDistrictForMainDB = district => {
const {isActive, lastRecordDate, ...districtRest} = district
districtRest.updateDate = new Date(districtRest.updateDate)
districtRest.config = districtRest.config || {}
return districtRest
}

const formatDistrictForExploitationDB = district => (
{
codeCommune: district.meta.insee.cog,
banId: district.id,
nomCommune: district.labels.find(label => label.isoCode === 'fra').value || district.labels[0].value,
}
)

main()
Loading