SvelteKit 的新手,正在努力调整来自 Node/Express 服务器的端点以使其更通用,以便能够利用 SvelteKit 适配器。端点通过 node-postgresql 下载存储在数据库中的文件。
我在 Node/Express 中的功能端点如下所示:
import stream from 'stream'
import db from '../utils/db'
export async function download(req, res) {
const _id = req.params.id
const sql = "SELECT _id, name, type, data FROM files WHERE _id = $1;"
const { rows } = await db.query(sql, [_id])
const file = rows[0]
const fileContents = Buffer.from(file.data, 'base64')
const readStream = new stream.PassThrough()
readStream.end(fileContents)
res.set('Content-disposition', `attachment; filename=${file.name}`)
res.set('Content-Type', file.type)
readStream.pipe(res)
}
到目前为止,这是我在 SvelteKit 中为 [filenum].json.ts 提供的内容......
import stream from 'stream'
import db from '$lib/db'
export async function get({ params }): Promise<any> {
const { filenum } = params
const { rows } = await db.query('SELECT _id, name, type, data FROM files WHERE _id = $1;', [filenum])
if (rows) {
const file = rows[0]
const fileContents = Buffer.from(file.data, 'base64')
const readStream = new stream.PassThrough()
readStream.end(fileContents)
let body
readStream.pipe(body)
return {
headers: {
'Content-disposition': `attachment; filename=${file.name}`,
'Content-type': file.type
},
body
}
}
}
在不创建对 Node 的依赖的情况下,使用 SvelteKit 执行此操作的正确方法是什么?根据SvelteKit 的端点文档,
我们不会与您可能在 Node 的 http 模块或 Express 等框架中熟悉的 req/res 对象进行交互,因为它们仅在某些平台上可用。相反,SvelteKit 将返回的对象转换为您将应用程序部署到的平台所需的任何内容。