Write a typescript nextjs module that implements api handler which returns the latest document from firestore collection "people". Firestore initialized and can be imported from '@db' package. Don't forget to provide file path where to paste the code. Ask more questions if something is not clear. Answer in json like this: {"additionalQuestions"?: string[], modules?: Array<{code: string, filePath: string}> }
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here is a TypeScript Next.js module that implements an API handler to return the latest document from a Firestore collection called "people". The Firestore instance is imported from the '@db' package.
typescript
// lib/api/people.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { db } from '@db'
import { collection, getDocs, query, orderBy, doc, getDoc } from 'firebase/firestore'
type Data = {
name?: string
email?: string
}
const handler = async (
req: NextApiRequest,
res: NextApiResponse<Data>
) => {
try {
const peopleCollection = collection(db, 'people')
const q = query(peopleCollection, orderBy('createdAt', 'desc'))
const querySnapshot = await getDocs(q)
if (querySnapshot.empty) {
res.status(404).json({ name: 'No data found', email: 'No data found' })
return
}
const lastDoc = querySnapshot.docs[0]
const lastDocData = await getDoc(lastDoc)
const data = lastDocData.data() as Data
res.status(200).json(data)
} catch (error) {
res.status(500).json({ error: 'An error occurred' })
}
}
export default handler
To use this module, save it in a file named lib/api/people.ts. Make sure you have the @db package installed and properly configured to use your Firestore instance.
This module exports a handler function that can be used in your Next.js API routes. It retrieves the latest document from the "people" collection in Firestore and returns its data. If no documents are found, it returns a 404 response. If an error occurs, it returns a 500 response.
You can use this module in your Next.js API route like this:
typescript
// pages/api/people.ts
import { NextApiRequest, NextApiResponse } from 'next'
import handler from '../../lib/api/people'
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
return handler(req, res)
}
This code assumes you have a Firestore collection called "people" and the necessary Firestore initialization in the @db package. Make sure to replace the import statement with the correct path to your Firestore instance.
Additional questions:
What is the expected data format of the documents in the "people" collection?
Should the @db package be installed locally or globally?
Are there any specific security rules for the "people" collection?