Skip to content

Feature request: Provide a helper function to decode a base64 encoded payload #4412

@sdangol

Description

@sdangol

Use case

When working with Kinesis data streams, I want to extend my schema and decode a base64 encoded payload. Currently, I have to do this manually.

import { KinesisDataStreamRecordPayload } from '@aws-lambda-powertools/parser/schemas/kinesis';
import { fromBase64 } from '@aws-lambda-powertools/commons/utils/base64';
import { gunzipSync } from 'node:zlib';
import { z } from 'zod';

const decoder = new TextDecoder();
const decompress = (data: string): string => {
try {
  return JSON.parse(gunzipSync(fromBase64(data, 'base64')).toString('utf8'));
} catch {
  return data;
}
};

const extendedSchema = KinesisDataStreamRecordPayload.extend({ 
  data: z.string().transform((data) => {
  const decompressed = decompress(data);
  const decoded = decoder.decode(fromBase64(data, 'base64'));
  try {
    // If data was not compressed, try to parse it as JSON otherwise it must be string
    return decompressed === data ? JSON.parse(decoded) : decompressed;
  } catch {
    return decoded;
  }
})
});
type _ExtendedKinesisDataStream = z.infer<typeof extendedSchema>;

Solution/User Experience

It would be easier to do this if there was a helper function similar to the JSONStringified helper. So that, the experience would be

import { Base64Encoded } from '@aws-lambda-powertools/parser/helpers';
import { KinesisDataStreamRecordPayload } from '@aws-lambda-powertools/parser/schemas/kinesis';
import { z } from 'zod';

const extendedSchema = KinesisDataStreamRecordPayload.extend({ 
  data: Base64Encoded(z.string())
});
type _ExtendedKinesisDataStream = z.infer<typeof extendedSchema>;

Alternative solutions

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

Labels

feature-requestThis item refers to a feature request for an existing or new utilityparserThis item relates to the Parser Utilitypending-releaseThis item has been merged and will be released soon

Type

No type

Projects

Status

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions