Skip to content

Commit

Permalink
fix: More explicitly reject invalid ids.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenh committed May 2, 2024
1 parent 6c3571a commit 3bf7c84
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
2 changes: 1 addition & 1 deletion packages/orm/src/EntityManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,7 @@ export class EntityManager<C = unknown, Entity extends EntityW = EntityW> {
id = typeOrId;
} else {
type = typeOrId;
id = id || fail();
id = id || fail(`Invalid id for ${typeOrId.name}: ${id}`);
}
const meta = getMetadata(type);
const tagged = toTaggedId(meta, id);
Expand Down
7 changes: 6 additions & 1 deletion packages/orm/src/createOrUpdatePartial.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isPlainObject } from "joist-utils";
import { Entity, isEntity } from "./Entity";
import { EntityManager, IdOf, MaybeAbstractEntityConstructor, OptIdsOf, OptsOf, isKey } from "./EntityManager";
import { getMetadata } from "./EntityMetadata";
Expand Down Expand Up @@ -140,10 +141,14 @@ export async function createOrUpdatePartial<T extends Entity>(

const entities = await Promise.all(
toArray(value).map(async (value: any) => {
if (!value || isEntity(value)) {
if (isEntity(value)) {
return value;
} else if (isKey(value)) {
return await em.load(field.otherMetadata().cstr, value);
} else if (value === null || value === undefined) {
return undefined;
} else if (!isPlainObject(value)) {
throw new Error(`Invalid value ${value}`);
} else {
// Look for `delete: true/false` and `remove: true/false` markers
const deleteMarker: any = allowDelete && value["delete"];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import {
insertTag,
select,
} from "@src/entities/inserts";
import { Author, Book, ImageType } from "./entities";

import { newEntityManager } from "@src/testEm";
import { Author, Book, ImageType } from "./entities";

describe("EntityManager.createOrUpdatePartial", () => {
it("can create new entity with valid data", async () => {
Expand Down Expand Up @@ -372,6 +371,16 @@ describe("EntityManager.createOrUpdatePartial", () => {
});
});

describe("m2m", () => {
it("rejects invalid ids", async () => {
const em = newEntityManager();
const result = em.createOrUpdatePartial(Author, {
tags: ["", ""],
});
await expect(result).rejects.toThrow("Invalid id for Tag");
});
});

it("createOrUpdatePartial doesnt allow unknown fields to be passed", async () => {
const em = newEntityManager();
// Given an opt `publisherTypo` (instead of `publisher`) that don't match exactly what Author supports
Expand Down

0 comments on commit 3bf7c84

Please sign in to comment.