Skip to content

Commit

Permalink
fix item api & remove unnecessary code
Browse files Browse the repository at this point in the history
  • Loading branch information
lyc8503 committed Oct 17, 2023
1 parent f29f91e commit c574e9e
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 55 deletions.
37 changes: 3 additions & 34 deletions src/pages/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,10 @@ export default async function handler(req: NextRequest): Promise<Response> {
return new Response('OK')
}

// If method is GET, then the API is a normal request to the OneDrive API for files or folders
const { path = '/', raw = false, next = '', sort = '' } = Object.fromEntries(req.nextUrl.searchParams)
// TODO: Set edge function caching for faster load times

// Set edge function caching for faster load times, check docs:
// https://vercel.com/docs/concepts/functions/edge-caching
// TODO
// res.setHeader('Cache-Control', apiConfig.cacheControlHeader)
// If method is GET, then the API is a normal request to the OneDrive API for files or folders
const { path = '/', next = '', sort = '' } = Object.fromEntries(req.nextUrl.searchParams)

// Sometimes the path parameter is defaulted to '[...path]' which we need to handle
if (path === '[...path]') {
Expand Down Expand Up @@ -209,41 +206,13 @@ export default async function handler(req: NextRequest): Promise<Response> {
if (code !== 200) {
return new Response(JSON.stringify({ error: message }), { status: code })
}
// If message is empty, then the path is not protected.
// Conversely, protected routes are not allowed to serve from cache.
// TODO:
// if (message !== '') {
// res.setHeader('Cache-Control', 'no-cache')
// }

const requestPath = encodePath(cleanPath)
// Handle response from OneDrive API
const requestUrl = `${apiConfig.driveApi}/root${requestPath}`
// Whether path is root, which requires some special treatment
const isRoot = requestPath === ''

// Go for file raw download link, add CORS headers, and redirect to @microsoft.graph.downloadUrl
// (kept here for backwards compatibility, and cache headers will be reverted to no-cache)
if (raw) {
// TODO
// await runCorsMiddleware(req, res)
// res.setHeader('Cache-Control', 'no-cache')

const { data } = await axios.get(requestUrl, {
headers: { Authorization: `Bearer ${accessToken}` },
params: {
// OneDrive international version fails when only selecting the downloadUrl (what a stupid bug)
select: 'id,@microsoft.graph.downloadUrl',
},
})

if ('@microsoft.graph.downloadUrl' in data) {
return Response.redirect(data['@microsoft.graph.downloadUrl'])
} else {
return new Response(JSON.stringify({ error: 'No download url found.' }), { status: 404 })
}
}

// Querying current path identity (file or folder) and follow up query childrens in folder
try {
const { data: identityData } = await axios.get(requestUrl, {
Expand Down
18 changes: 7 additions & 11 deletions src/pages/api/item.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,34 @@
import axios from 'redaxios'
import type { NextApiRequest, NextApiResponse } from 'next'

import { getAccessToken } from '.'
import apiConfig from '../../../config/api.config'
import { NextRequest, NextResponse } from 'next/server'

export const runtime = 'edge'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
export default async function handler(req: NextRequest): Promise<Response> {
// Get access token from storage
const accessToken = await getAccessToken()

// Get item details (specifically, its path) by its unique ID in OneDrive
const { id = '' } = req.query
const { id = '' } = Object.fromEntries(req.nextUrl.searchParams)

// Set edge function caching for faster load times, check docs:
// https://vercel.com/docs/concepts/functions/edge-caching
res.setHeader('Cache-Control', apiConfig.cacheControlHeader)
// TODO: Set edge function caching for faster load times

if (typeof id === 'string') {
const itemApi = `${apiConfig.driveApi}/items/${id}`

try {
const { data } = await axios.get(itemApi, {
headers: { Authorization: `Bearer ${accessToken}` },
params: {
select: 'id,name,parentReference',
},
})
res.status(200).json(data)
return NextResponse.json(data)
} catch (error: any) {
res.status(error?.response?.status ?? 500).json({ error: error?.response?.data ?? 'Internal server error.' })
return new Response(JSON.stringify({ error: error?.response?.data ?? 'Internal server error.' }), { status: error?.response?.status ?? 500 })
}
} else {
res.status(400).json({ error: 'Invalid driveItem ID.' })
return new Response(JSON.stringify({ error: 'Invalid driveItem ID.' }), { status: 400 })
}
return
}
5 changes: 1 addition & 4 deletions src/pages/api/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,7 @@ export default async function handler(req: NextRequest): Promise<Response> {
// Query parameter from request
const { q: searchQuery = '' } = Object.fromEntries(req.nextUrl.searchParams)

// Set edge function caching for faster load times, check docs:
// https://vercel.com/docs/concepts/functions/edge-caching
// TODO
// res.setHeader('Cache-Control', apiConfig.cacheControlHeader)
// TODO: Set edge function caching for faster load times

if (typeof searchQuery === 'string') {
// Construct Microsoft Graph Search API URL, and perform search only under the base directory
Expand Down
7 changes: 1 addition & 6 deletions src/pages/api/thumbnail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ export default async function handler(req: NextRequest): Promise<Response> {
// Get item thumbnails by its path since we will later check if it is protected
const { path = '', size = 'medium', odpt = '' } = Object.fromEntries(req.nextUrl.searchParams)

// Set edge function caching for faster load times, if route is not protected, check docs:
// https://vercel.com/docs/concepts/functions/edge-caching
// TODO
// TODO: Set edge function caching for faster load times, if route is not protected
// if (odpt === '') res.setHeader('Cache-Control', apiConfig.cacheControlHeader)

// Check whether the size is valid - must be one of 'large', 'medium', or 'small'
Expand All @@ -47,9 +45,6 @@ export default async function handler(req: NextRequest): Promise<Response> {
// If message is empty, then the path is not protected.
// Conversely, protected routes are not allowed to serve from cache.
// TODO
// if (message !== '') {
// res.setHeader('Cache-Control', 'no-cache')
// }

const requestPath = encodePath(cleanPath)
// Handle response from OneDrive API
Expand Down

0 comments on commit c574e9e

Please sign in to comment.