|
| 1 | +import { Collection, Identifier, JSCodeshift, ObjectPattern, Property } from "jscodeshift"; |
| 2 | + |
| 3 | +import { AddV3ClientModuleOptions } from "./addV3ClientModule"; |
| 4 | +import { getRequireVariableDeclaration } from "./getRequireVariableDeclaration"; |
| 5 | + |
| 6 | +export const addV3ClientRequire = ( |
| 7 | + j: JSCodeshift, |
| 8 | + source: Collection<any>, |
| 9 | + { v2ClientName, v3ClientName, v3ClientPackageName }: AddV3ClientModuleOptions |
| 10 | +): void => { |
| 11 | + const v3ClientNameIdentifier = j.identifier(v3ClientName); |
| 12 | + const v3ClientNameProperty = j.property.from({ |
| 13 | + kind: "init", |
| 14 | + key: v3ClientNameIdentifier, |
| 15 | + shorthand: true, |
| 16 | + value: v3ClientNameIdentifier, |
| 17 | + }); |
| 18 | + |
| 19 | + const existingRequires = source.find(j.VariableDeclarator, { |
| 20 | + id: { type: "ObjectPattern" }, |
| 21 | + init: { |
| 22 | + type: "CallExpression", |
| 23 | + callee: { type: "Identifier", name: "require" }, |
| 24 | + arguments: [{ type: "Literal", value: v3ClientPackageName }], |
| 25 | + }, |
| 26 | + }); |
| 27 | + |
| 28 | + // Require decleration already exists. |
| 29 | + if (existingRequires.size()) { |
| 30 | + existingRequires.forEach((nodePath) => { |
| 31 | + // Append to existing require if property not present. |
| 32 | + if ( |
| 33 | + !(nodePath.value.id as ObjectPattern).properties.find( |
| 34 | + (property) => ((property as Property).key as Identifier).name === v3ClientName |
| 35 | + ) |
| 36 | + ) { |
| 37 | + (nodePath.value.id as ObjectPattern).properties.push(v3ClientNameProperty); |
| 38 | + } |
| 39 | + }); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + // Insert after default require if present. If not, insert after client require. |
| 44 | + const clientRequireValue = `aws-sdk/clients/${v2ClientName.toLowerCase()}`; |
| 45 | + const defaultRequireVarDeclaration = getRequireVariableDeclaration(j, source, "aws-sdk"); |
| 46 | + const clientRequireVarDeclaration = getRequireVariableDeclaration(j, source, clientRequireValue); |
| 47 | + |
| 48 | + const requireVarDeclaration = |
| 49 | + defaultRequireVarDeclaration.size() > 0 |
| 50 | + ? defaultRequireVarDeclaration |
| 51 | + : clientRequireVarDeclaration; |
| 52 | + requireVarDeclaration.insertAfter( |
| 53 | + j.variableDeclaration("const", [ |
| 54 | + j.variableDeclarator( |
| 55 | + j.objectPattern([v3ClientNameProperty]), |
| 56 | + j.callExpression(j.identifier("require"), [j.literal(v3ClientPackageName)]) |
| 57 | + ), |
| 58 | + ]) |
| 59 | + ); |
| 60 | +}; |
0 commit comments