async function deidentifyWithDateShift()

in dlp/deidentifyWithDateShift.js [99:175]


  async function deidentifyWithDateShift() {
    // Read and parse a CSV file
    const csvLines = fs
      .readFileSync(inputCsvFile)
      .toString()
      .split('\n')
      .filter(line => line.includes(','));
    const csvHeaders = csvLines[0].split(',');
    const csvRows = csvLines.slice(1);

    // Construct the table object
    const tableItem = {
      table: {
        headers: csvHeaders.map(header => {
          return {name: header};
        }),
        rows: csvRows.map(row => rowToProto(row)),
      },
    };

    // Construct DateShiftConfig
    const dateShiftConfig = {
      lowerBoundDays: lowerBoundDays,
      upperBoundDays: upperBoundDays,
    };

    if (contextFieldId && keyName && wrappedKey) {
      dateShiftConfig.context = {name: contextFieldId};
      dateShiftConfig.cryptoKey = {
        kmsWrapped: {
          wrappedKey: wrappedKey,
          cryptoKeyName: keyName,
        },
      };
    } else if (contextFieldId || keyName || wrappedKey) {
      throw new Error(
        'You must set either ALL or NONE of {contextFieldId, keyName, wrappedKey}!'
      );
    }

    // Construct deidentification request
    const request = {
      parent: `projects/${projectId}/locations/global`,
      deidentifyConfig: {
        recordTransformations: {
          fieldTransformations: [
            {
              fields: dateFields,
              primitiveTransformation: {
                dateShiftConfig: dateShiftConfig,
              },
            },
          ],
        },
      },
      item: tableItem,
    };

    // Run deidentification request
    const [response] = await dlp.deidentifyContent(request);
    const tableRows = response.item.table.rows;

    // Write results to a CSV file
    tableRows.forEach((row, rowIndex) => {
      const rowValues = row.values.map(
        value =>
          value.stringValue ||
          `${value.dateValue.month}/${value.dateValue.day}/${value.dateValue.year}`
      );
      csvLines[rowIndex + 1] = rowValues.join(',');
    });
    csvLines.push('');
    fs.writeFileSync(outputCsvFile, csvLines.join('\n'));

    // Print status
    console.log(`Successfully saved date-shift output to ${outputCsvFile}`);
  }