Skip to content

Commit

Permalink
add-contact-id-to-user-docs migration
Browse files Browse the repository at this point in the history
  • Loading branch information
m5r committed Apr 2, 2024
1 parent 4dbe6b1 commit ab09351
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions api/src/migrations/add-contact-id-to-user-docs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const db = require('../db');
const logger = require('../logger');

const BATCH_SIZE = 1;

const runBatch = async (skip = 0) => {
const options = {
include_docs: true,
limit: BATCH_SIZE,
key: ['user-settings'],
skip,
};
const { rows } = await db.medic.query('medic-client/doc_by_type', options);
if (!rows.length) {
return;
}

for (const row of rows) {
const { _id, contact_id } = row.doc;
try {
const user = await db.users.get(_id);
user.contact_id = contact_id;
await db.users.put(user);
} catch (error) {
if (error.status !== 404) {
throw error;
}
logger.warn(`User with id "${_id}" does not exist anymore, skipping it.`);
}
}

if (rows.length < BATCH_SIZE) {
return;
}

return runBatch(skip + BATCH_SIZE);
};

module.exports = {
name: 'add-contact-id-to-user-docs',
created: new Date(2024, 5, 2),
run: runBatch,
};

0 comments on commit ab09351

Please sign in to comment.