fixMongodbImport.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const { getLastImport } = require('./utils')
  2. module.exports = function (fileInfo, api) {
  3. const j = api.jscodeshift
  4. const root = j(fileInfo.source)
  5. const body = root.get().value.program.body
  6. // Fix mongodb-legacy import
  7. root
  8. .find(j.ImportDeclaration, {
  9. source: { value: 'mongodb-legacy' },
  10. specifiers: [{ imported: { name: 'ObjectId' } }],
  11. })
  12. .forEach(path => {
  13. // Create new import declaration
  14. const newImport = j.importDeclaration(
  15. [j.importDefaultSpecifier(j.identifier('mongodb'))],
  16. j.literal('mongodb-legacy')
  17. )
  18. // Create new constant declaration
  19. const newConst = j.variableDeclaration('const', [
  20. j.variableDeclarator(
  21. j.objectPattern([
  22. j.property(
  23. 'init',
  24. j.identifier('ObjectId'),
  25. j.identifier('ObjectId')
  26. ),
  27. ]),
  28. j.identifier('mongodb')
  29. ),
  30. ])
  31. // Replace the old import with the new import
  32. j(path).replaceWith(newImport)
  33. // Insert the new constant declaration after the last import
  34. const lastImportIndex = getLastImport(body)
  35. body.splice(lastImportIndex + 1, 0, newConst)
  36. })
  37. return root.toSource({
  38. quote: 'single',
  39. })
  40. }