2022-01-18 18:25:18 +01:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next'
|
|
|
|
import { drive } from '@googleapis/drive'
|
2022-05-13 09:18:25 -07:00
|
|
|
import { OAuth2Client } from 'googleapis-common'
|
2022-01-18 18:25:18 +01:00
|
|
|
import { getAuthenticatedGoogleClient } from 'libs/google-sheets'
|
2022-05-03 06:39:54 -07:00
|
|
|
import { badRequest, methodNotAllowed, notAuthenticated } from 'utils'
|
|
|
|
import { setUser, withSentry } from '@sentry/nextjs'
|
2022-03-04 17:21:01 +01:00
|
|
|
import { getAuthenticatedUser } from 'services/api/utils'
|
2022-01-18 18:25:18 +01:00
|
|
|
|
|
|
|
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
|
2022-03-04 17:21:01 +01:00
|
|
|
const user = await getAuthenticatedUser(req)
|
|
|
|
if (!user) return notAuthenticated(res)
|
2022-01-18 18:25:18 +01:00
|
|
|
|
2022-03-02 07:41:08 +01:00
|
|
|
setUser({ email: user.email ?? undefined, id: user.id })
|
2022-01-18 18:25:18 +01:00
|
|
|
if (req.method === 'GET') {
|
2022-04-09 08:05:30 -05:00
|
|
|
const credentialsId = req.query.credentialsId as string | undefined
|
|
|
|
if (!credentialsId) return badRequest(res)
|
2022-01-18 18:25:18 +01:00
|
|
|
const auth = await getAuthenticatedGoogleClient(user.id, credentialsId)
|
2022-03-04 14:40:13 +01:00
|
|
|
if (!auth)
|
|
|
|
return res.status(404).send("Couldn't find credentials in database")
|
2022-02-25 18:30:14 +01:00
|
|
|
const response = await drive({
|
2022-01-18 18:25:18 +01:00
|
|
|
version: 'v3',
|
2022-05-13 09:18:25 -07:00
|
|
|
auth: auth.client as unknown as OAuth2Client,
|
2022-01-18 18:25:18 +01:00
|
|
|
}).files.list({
|
|
|
|
q: "mimeType='application/vnd.google-apps.spreadsheet'",
|
|
|
|
fields: 'nextPageToken, files(id, name)',
|
|
|
|
})
|
2022-02-25 18:30:14 +01:00
|
|
|
return res.send(response.data)
|
2022-01-18 18:25:18 +01:00
|
|
|
}
|
|
|
|
return methodNotAllowed(res)
|
|
|
|
}
|
|
|
|
|
2022-02-14 10:57:57 +01:00
|
|
|
export default withSentry(handler)
|