ts-morph#PropertyAssignment TypeScript Examples

The following examples show how to use ts-morph#PropertyAssignment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: update-object-property.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
export function updateObjectProperty(args: {
  expression: ObjectLiteralExpression;
  name: string;
  value: string | number | boolean | undefined;
}) {
  const { expression, name, value } = args;
  let propertyAssignment = expression.getProperty(name) as
    | PropertyAssignment
    | undefined;

  if (value === undefined) {
    if (propertyAssignment) {
      propertyAssignment.remove();
    }
    return;
  }

  if (!propertyAssignment) {
    propertyAssignment = expression.addProperty({
      name,
      kind: StructureKind.PropertyAssignment,
      initializer: 'undefined',
    }) as PropertyAssignment;
  }

  propertyAssignment.setInitializer(JSON.stringify(value));
}
Example #2
Source File: instructions.ts    From adonis5-jwt with MIT License 4 votes vote down vote up
/**
 * Makes the auth config file
 */
async function editConfig(
    projectRoot: string,
    app: ApplicationContract,
    sink: typeof sinkStatic,
    state: InstructionsState
) {
    const configDirectory = app.directoriesMap.get("config") || "config";
    const configPath = join(configDirectory, "auth.ts");

    let tokenProvider;
    if (state.tokensProvider === "redis") {
        tokenProvider = Writers.object({
            type: "'jwt'",
            driver: "'redis'",
            redisConnection: "'local'",
            foreignKey: "'user_id'",
        });
    } else {
        tokenProvider = Writers.object({
            type: "'api'",
            driver: "'database'",
            table: "'jwt_tokens'",
            foreignKey: "'user_id'",
        });
    }

    let provider;
    if (state.provider === "database") {
        provider = Writers.object({
            driver: "'database'",
            identifierKey: "'id'",
            uids: "['email']",
            usersTable: `'${state.usersTableName}'`,
        });
    } else if (state.provider === "lucid") {
        provider = Writers.object({
            driver: '"lucid"',
            identifierKey: '"id"',
            uids: "[]",
            model: `() => import('${state.usersModelNamespace}')`,
        });
    } else {
        throw new Error(`Invalid state.provider: ${state.provider}`);
    }

    //Instantiate ts-morph
    const project = await getTsMorphProject(projectRoot);
    const authConfigFile = project.getSourceFileOrThrow(configPath);

    //Remove Env import, if already present
    authConfigFile.getImportDeclaration("@ioc:Adonis/Core/Env")?.remove();

    //Add Env import
    authConfigFile.addImportDeclaration({
        defaultImport: "Env",
        moduleSpecifier: "@ioc:Adonis/Core/Env",
    });

    const variable = authConfigFile
        ?.getVariableDeclarationOrThrow("authConfig")
        .getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
    let guardsProperty = variable?.getPropertyOrThrow("guards") as PropertyAssignment;
    let guardsObject = guardsProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);

    //Remove JWT config, if already present
    guardsObject.getProperty("jwt")?.remove();

    //Add JWT config
    guardsObject?.addPropertyAssignment({
        name: "jwt",
        initializer: Writers.object({
            driver: '"jwt"',
            publicKey: `Env.get('JWT_PUBLIC_KEY', '').replace(/\\\\n/g, '\\n')`,
            privateKey: `Env.get('JWT_PRIVATE_KEY', '').replace(/\\\\n/g, '\\n')`,
            persistJwt: `${state.persistJwt ? "true" : "false"}`,
            jwtDefaultExpire: `'${state.jwtDefaultExpire}'`,
            refreshTokenDefaultExpire: `'${state.refreshTokenDefaultExpire}'`,
            tokenProvider: tokenProvider,
            provider: provider,
        }),
    });

    authConfigFile.formatText();
    await authConfigFile?.save();

    sink.logger.action("update").succeeded(configPath);
}