新的SvelteKit,并努力调整来自Node/Express服务器的端点,使其更通用,以便能够利用SvelteKit适配器。端点通过节点-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)
}这是我在filenum.json.ts in SvelteKit到目前为止.
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
}
}
}在不创建节点依赖项的情况下,使用SvelteKit进行此操作的正确方法是什么?根据SvelteKit的端点文档,
我们不会与Node的http模块或像Express这样的框架中熟悉的req/res对象交互,因为它们只能在特定的平台上使用。相反,SvelteKit将返回的对象转换为部署应用程序的平台所需的任何东西。
发布于 2021-06-04 16:37:42
更新:错误是在SvelteKit中修复的。这是工作的更新代码:
// src/routes/api/file/_file.controller.ts
import { query } from '../_db'
type GetFileResponse = (fileNumber: string) => Promise<{
headers: {
'Content-Disposition': string
'Content-Type': string
}
body: Uint8Array
status?: number
} | {
status: number
headers?: undefined
body?: undefined
}>
export const getFile: GetFileResponse = async (fileNumber: string) => {
const { rows } = await query(`SELECT _id, name, type, data FROM files WHERE _id = $1;`, [fileNumber])
if (rows) {
const file = rows[0]
return {
headers: {
'Content-Disposition': `attachment; filename="${file.name}"`,
'Content-Type': file.type
},
body: new Uint8Array(file.data)
}
} else return {
status: 404
}
}和
// src/routes/api/file/[filenum].ts
import type { RequestHandler } from '@sveltejs/kit'
import { getFile } from './_file.controller'
export const get: RequestHandler = async ({ params }) => {
const { filenum } = params
const fileResponse = await getFile(filenum)
return fileResponse
}https://stackoverflow.com/questions/67639447
复制相似问题