To create a TypeScript Next.js module that implements an API handler for fetching the latest document from the Firestore collection "people", you can follow the code snippet below. Make sure to install the necessary dependencies and place the code in the appropriate file.
{
"additionalQuestions": [],
"modules": [
{
"code": `import { getFirestore } from '@db';
export default async function handler(req, res) {
const db = getFirestore();
const collection = db.collection('people');
const snapshot = await collection.orderBy('createdAt', 'desc').limit(1).get();
const doc = snapshot.docs;
if (!doc.exists) {
res.status(404).json({ message: 'No document found' });
} else {
res.status(200).json(doc.data());
}
}
},
{
"filePath": "pages/api/[handler].ts",
"code": ""
}
]
}
Place this code in the pages/api/[handler].ts file, replacing [handler] with a suitable API handler name (e.g., people). Make sure to import the @db package, which should contain the Firestore instance.
To ensure proper initialization and usage of Firestore, follow these steps:
- Install the necessary dependencies:
npm install --save @types/firestore @firebase/firestore
- Create a
db.ts file in your project and initialize Firestore:
import { initializeFirestore } from '@firebase/firestore';
const db = initializeFirestore({
// Your Firestore configuration here
});
export { db };
- Import the Firestore instance in your API handler file:
import { getFirestore } from '@db';
- Use the Firestore instance to fetch the latest document from the "people" collection as shown in the code snippet above.
If you encounter any issues or need further clarification, feel free to ask.