Fastify Route, Handler, Service Codes

Fastify Route code

  server.get(
    "/googlelink/:id",
    {
      schema: {
        params: $Sref("idParamsSchema"),
      },
    },
    fetchGoogleUrlBySurveyIdHandler
  );

Fastify sample controller code

export async function fetchGoogleUrlBySurveyIdHandler(
  request: FastifyRequest<{
    Params: IdParamInput;
  }>,
  reply: FastifyReply
) {

  let url;
  
  try {
    url =  await getGoogleUrlBySurveyId(request.params.id);
  } catch (e: any) {
    console.error(e);
    reply.code(500).send({ success: false, message: e.message });
    return;
  }
  
  if ("error" in url){
    reply.code(404).send({ success: false, data: url});
  }else{
    reply.code(201).send({ success: true, data: url});
  }
  
}

Fastify sample service code

export async function getGoogleUrlBySurveyId(id: string) {
  const survey = await prisma.survey.findUnique({
    where: {
      id,
    },
    select: {
      teamId: true,
    },
  });

  if(survey){
    const team = await prisma.team.findUnique({
      where: {
        id: survey.teamId
      },
      select: {
        googleLink: true,
      },
    });

    return team;

  }else{
    return { error: "Survey not found"}
  }

}

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *