Files
overleaf-cep/services/web/transform/cjs-to-esm/codemods/fixMongodbImport.js
Andrew Rumble eda1bd697f Merge pull request #27958 from overleaf/ar-change-esm-codemod-to-use-vitest-and-general-refactor
[web] change esm codemod to use vitest and general refactor

GitOrigin-RevId: 7f8c699b160ee0b7ff991d6284cb126165694c4f
2025-09-17 08:04:57 +00:00

47 lines
1.2 KiB
JavaScript

const { getLastImport } = require('./utils')
module.exports = function (fileInfo, api) {
const j = api.jscodeshift
const root = j(fileInfo.source)
const body = root.get().value.program.body
// Fix mongodb-legacy import
root
.find(j.ImportDeclaration, {
source: { value: 'mongodb-legacy' },
specifiers: [{ imported: { name: 'ObjectId' } }],
})
.forEach(path => {
// Create new import declaration
const newImport = j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('mongodb'))],
j.literal('mongodb-legacy')
)
// Create new constant declaration
const newConst = j.variableDeclaration('const', [
j.variableDeclarator(
j.objectPattern([
j.property(
'init',
j.identifier('ObjectId'),
j.identifier('ObjectId')
),
]),
j.identifier('mongodb')
),
])
// Replace the old import with the new import
j(path).replaceWith(newImport)
// Insert the new constant declaration after the last import
const lastImportIndex = getLastImport(body)
body.splice(lastImportIndex + 1, 0, newConst)
})
return root.toSource({
quote: 'single',
})
}