Nick Shoemake
Nick Shoemake

Reputation: 11

Prisma Typing Error Using Prisma's Generated Types with Server Actions

I have the following models:

model Resident {
// Identification and Metadata
id        String   u/id u/unique u/default(uuid()) u/db.Uuid
createdAt DateTime u/default(now())
updatedAt DateTime u/updatedAt

// Personal Information
firstName       String
middleName      String?
lastName        String

// ... bunch of other fields

// Relationships
ethnicity                        Ethnicity              u/relation(fields: [ethnicityId], references: [id])
ethnicityId                      String                 u/db.Uuid
// ... bunch of other fields
}

model Ethnicity {
id        String     u/id u/unique u/default(uuid()) u/db.Uuid
createdAt DateTime   u/default(now())
updatedAt DateTime   u/updatedAt
name      String     u/unique
residents Resident[]
}

I also have the following server action:

export async function createResident(
  data: ResidentCreateInput,
  userId: string,
): Promise<ResidentWithHomes> {
  try {
    const resident = await prisma.resident.create({
      data: {
        ...data,
        createdBy: { connect: { id: userId } },
        ethnicity: {
          connectOrCreate: {
            where: { name: data.ethnicity.name },
            create: { name: data.ethnicity.name },
          },
        },
        // ... more code
    });

    return resident;
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      throw new Error(`Database request failed: ${error.message}`);
    } else if (error instanceof Prisma.PrismaClientValidationError) {
      throw new Error(
        `Validation failed for the data provided: ${error.message}`,
      );
    } else {
      throw new Error('An unexpected error occurred while creating a resident');
    }
  }
}

I get the following type error:

Property 'name' does not exist on type 'EthnicityCreateNestedOneWithoutResidentsInput'.

My data object matches the expected data structure (I think)... for example:

{
    "firstName": "example",
    "middleName": "example",
    "lastName": "example",
    // ... more fields
    "ethnicity": {
        "name": "example"
    },
    // ... more fields
}

Should I not be using ResidentCreateInput as my data type here? I try to keep my API layer separate from my DB layer, but server actions interact directly with the DB and figured that utilizing Prisma's built in types would be appropriate here.

I've tried flattening the data object and just passing the flattened data, but get a different typing error.

Upvotes: 1

Views: 53

Answers (0)

Related Questions