2

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 将返回的对象转换为您将应用程序部署到的平台所需的任何内容。

4

1 回答 1

1

更新:该错误已在 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
}
于 2021-06-04T16:37:42.177 回答