Skip to content

Instantly share code, notes, and snippets.

@TimMikeladze
Created April 18, 2023 16:30
Show Gist options
  • Save TimMikeladze/1e9ab5d83182d5c4e83d7f00352ee90a to your computer and use it in GitHub Desktop.
Save TimMikeladze/1e9ab5d83182d5c4e83d7f00352ee90a to your computer and use it in GitHub Desktop.
import { getSession } from 'next-auth/react';
import { findUserByEmailOrName, getMatches } from '../../graphql/resolvers';
import { createObjectCsvStringifier as createCsvStringifier } from 'csv-writer';
import AdmZip from 'adm-zip';
import { NextApiRequest, NextApiResponse } from 'next';
import isDowntime from '../../util/isDowntime';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
if (isDowntime()) {
res.status(503).send(`Downtime`);
return;
}
const session = await getSession({ req });
if (!session) {
res.status(401).json({ message: `Unauthenticated` });
return;
}
const user = await findUserByEmailOrName(
session.user.email || session.user.name,
);
const matches = await getMatches(user.id, null, true);
user.matches = matches;
const csvStringifier = createCsvStringifier({
header: [
{ id: `id`, title: `ID` },
{ id: `createdAt`, title: `createdAt` },
{ id: `gsp`, title: `GSP` },
{ id: `won`, title: `won` },
{ id: `myFighterId`, title: `myFighterId` },
{ id: `winnerId`, title: `winnerId` },
{ id: `participantIds`, title: `participantIds` },
{ id: `stageId`, title: `stageId` },
{ id: `rematched`, title: `rematched` },
],
});
const headerString = csvStringifier.getHeaderString();
const matchesString = csvStringifier.stringifyRecords(
matches.map((match) => ({
id: match.id,
createdAt: match.createdAt,
gsp: match.gsp,
won: match.won,
myFighterId: match.myFighterId,
winnerId: match.winnerId,
participantIds: match.participantIds,
stageId: match.stageId,
rematched: match.rematched,
})),
);
const zip = new AdmZip();
zip.addFile(
`matches.csv`,
Buffer.from(`${headerString}${matchesString}`, `utf8`),
``,
);
zip.addFile(`user.json`, Buffer.from(JSON.stringify(user), `utf8`), ``);
res.setHeader(`Content-Type`, `application/zip`);
res.setHeader(`Content-Disposition`, `attachment; filename=smashtracker.zip`);
res.send(zip.toBuffer());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment