【发布时间】:2021-08-10 19:59:48
【问题描述】:
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's Endpoint docs,
我们不会与您可能在 Node 的 http 模块或 Express 等框架中熟悉的 req/res 对象进行交互,因为它们仅在某些平台上可用。相反,SvelteKit 将返回的对象转换为您将应用部署到的平台所需的任何内容。
【问题讨论】:
-
为什么要移除节点依赖?端点在服务器上运行,对于所有适配器(静态适配器除外)无论如何都将在节点环境中。
-
SvelteKit 在kit.svelte.dev/docs#routing-endpoints 上的文档说:“我们不会与您可能熟悉的 Node 的 http 模块或 Express 等框架中的 req/res 对象进行交互,因为它们仅在某些平台。相反,SvelteKit 将返回的对象转换为您将应用程序部署到的平台所需的任何内容。"
-
是的,但这并不意味着您无法访问其他节点功能,只是 sveltekit 抽象出了 req/res 部分。
-
由于get方法中没有res,想知道如何调用readStream.pipe(res)。
-
把它放到另一个临时变量中?
标签: node.js express svelte node-postgres sveltekit