0

I'd like to pass a authorized Context type while I am doing a mutation, but how can I do it with nexus.js?

./src/types/Context.ts

import { PrismaClient } from "@prisma/client";

export interface Context {
  uid?: string | null;
  prisma: PrismaClient;
}

export interface AuthorizedContext extends Context {
  uid: string;
}

create Context function which is passed to Apollo Server

import prisma from "./prisma";
import { NextApiRequest } from "next";
import { loadIdToken } from "src/auth/firebaseAdmin";
import { Context } from "src/types/Context";
import { getAuth } from "firebase/auth";

export async function createContext({
  req,
}: {
  req: NextApiRequest;
}): Promise<Context> {
  const uid = await loadIdToken(req);

  const user = getAuth();
  if (user.currentUser?.uid === null) {
    console.log("user not logged in");
    return { prisma };
  }

  return {
    uid,
    prisma,
  };
}

This schema below is also passed to Apollo Server

src/graphql/schema.ts

import { makeSchema } from "nexus";
import { join } from "path";
import * as types from "./types";

const schema = makeSchema({
  types,
  contextType: {
    module: join(process.cwd(), "./src/types/Context.ts"),
    export: "Context",
  },
  outputs: {
    schema: join(process.cwd(), "./generated/schema.graphql"),
    typegen: join(process.cwd(), "./generated/nexus-typegen.d.ts"),
  },
});

export { schema };

nexus mutation:

export const createCoalDepot = extendType({
  type: "Mutation",
  definition: (t) => {
    t.field("createCoalDepot", {
      type: CoalDepot,
      args: { input: nonNull(CoalDepotInput), ctx: // pass AuthorizedContext Type here to use it in createCoalDepotResolver  },
      resolve: createCoalDepotResolver,
    });
  },
});

Here is the resolver where I got a error (1) got an userId: string | null | undefined Type 'string | null | undefined' is not assignable to type 'string'.

src/graphql/resolvers/coalDepotResolver.ts

export const createCoalDepotResolver: FieldResolver<
  "Mutation",
  "createCoalDepot"
> = async (_, { input }, { uid, prisma }) => {
  const newCoalDepot = await prisma.coalDepot.create({
    data: {
      address: input.address,
      image: input.image,
      latitude: input.coordinates?.latitude,
      longitude: input.coordinates?.longitude,
      coalDepotName: input.coalDepotName,
      mobilePhone: input.mobilePhone,
      landline: input.landline,
      coalDescAndAmount: input.coalDescAndAmount,
      userId: uid, // the error (1)
    },
  });
};
xxxbud
  • 95
  • 5

0 Answers0