Skip to content

Commit

Permalink
Support nested schemas in arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
tgandrews committed Mar 2, 2023
1 parent dc2f443 commit 86d8c48
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 10 deletions.
42 changes: 42 additions & 0 deletions src/index.test.ts
Expand Up @@ -325,6 +325,48 @@ describe("omanyd", () => {
expect(readThing?.a.b.date).toBeInstanceOf(Date);
expect(readThing?.a.b.date).toEqual(new Date("2023-03-02T11:49:00.000Z"));
});

it("should save and return dates nested within arrays", async () => {
interface Thing {
id: string;
list: {
date: Date;
}[];
}
const ThingStore = Omanyd.define<Thing>({
name: "arrayNestedDate",
hashKey: "id",
schema: Joi.object({
id: Omanyd.types.id(),
list: Joi.array()
.items(
Joi.object({
date: Joi.date().required(),
}).required()
)
.required(),
}),
});

await Omanyd.createTables();

const savedThing = await ThingStore.create({
list: [
{
date: new Date("2023-03-02T11:49:00.000Z"),
},
],
});
const readThing = await ThingStore.getByHashKey(savedThing.id);
expect(savedThing.list[0].date).toBeInstanceOf(Date);
expect(savedThing.list[0].date).toEqual(
new Date("2023-03-02T11:49:00.000Z")
);
expect(readThing?.list[0].date).toBeInstanceOf(Date);
expect(readThing?.list[0].date).toEqual(
new Date("2023-03-02T11:49:00.000Z")
);
});
});

describe("range key", () => {
Expand Down
29 changes: 19 additions & 10 deletions src/serializer.ts
Expand Up @@ -52,17 +52,26 @@ class Serializer {
return undefined;
}

const meta = schema.describe().metas?.[0]?.type;
switch (meta) {
case "SS":
return { SS: a };
default:
return {
L: a
.map((item) => this.any(item))
.filter(Boolean) as AWSDDB.AttributeValue[],
};
const description = schema.describe();
const meta = description.metas?.[0]?.type;
if (meta === "SS") {
return { SS: a };
}

const itemsSchema = schema.$_terms.items[0];
if (itemsSchema) {
return {
L: a
.map((item) => this.toDynamoValue(item, itemsSchema))
.filter(Boolean) as AWSDDB.AttributeValue[],
};
}

return {
L: a
.map((item) => this.any(item))
.filter(Boolean) as AWSDDB.AttributeValue[],
};
}

private any(value: any): AWSDDB.AttributeValue | undefined {
Expand Down

0 comments on commit 86d8c48

Please sign in to comment.