Skip to content

Commit a592b22

Browse files
committed
Support optional type (e.g. string | undefined, maybeString?: string)
Signed-off-by: moznion <moznion@mail.moznion.net>
1 parent 7b351f9 commit a592b22

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/dynamodb_primitive_types.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ export function dynamodbPrimitiveTypeFromTypeFlag(flag: ts.TypeFlags | undefined
2828
}
2929

3030
export function dynamodbPrimitiveTypeFromName(typeName: string | undefined): DynamodbPrimitiveTypes | undefined {
31+
if (typeName === undefined) {
32+
return undefined;
33+
}
34+
35+
const unionTypes: string[] = typeName.split('|').map(t => t.trim());
36+
const isUndefinedType = (t: string): boolean => t === 'undefined';
37+
// const isOptionalType = unionTypes.find(isUndefinedType);
38+
typeName = unionTypes.filter(t => !isUndefinedType(t)).join('|');
39+
3140
switch (typeName) {
3241
case 'string':
3342
return DynamodbPrimitiveTypes.String;

tests/transformer.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,4 +285,30 @@ describe('dynamodb record transform', () => {
285285
expect(record['tags']).toEqual({ M: { foo: { S: 'bar' }, buz: { S: 'qux' } } });
286286
expect(Object.keys(record)).toHaveLength(3);
287287
});
288+
289+
test('optional', () => {
290+
class Clazz {
291+
constructor(
292+
readonly optionalStr1: string | undefined,
293+
readonly optionalStr2: undefined | string,
294+
readonly optionalStr3?: string,
295+
) {}
296+
}
297+
298+
{
299+
const record: Record<keyof Clazz, AttributeValue> = dynamodbRecord<Clazz>(
300+
new Clazz(undefined, undefined, undefined),
301+
);
302+
expect(record['optionalStr1']).toEqual({ S: undefined });
303+
expect(record['optionalStr2']).toEqual({ S: undefined });
304+
expect(record['optionalStr3']).toEqual({ S: undefined });
305+
}
306+
307+
{
308+
const record: Record<keyof Clazz, AttributeValue> = dynamodbRecord<Clazz>(new Clazz('foo', 'bar', 'buz'));
309+
expect(record['optionalStr1']).toEqual({ S: 'foo' });
310+
expect(record['optionalStr2']).toEqual({ S: 'bar' });
311+
expect(record['optionalStr3']).toEqual({ S: 'buz' });
312+
}
313+
});
288314
});

0 commit comments

Comments
 (0)