SvelteKit端点:从Node / Express转换

4
我可以帮助您进行文字翻译。以下是需要翻译的内容:

我刚开始使用SvelteKit,并且正在尝试将一个节点/Express服务器的端点适应为通用型,以便能够利用SvelteKit适配器。该端点通过node-postgresql从数据库下载存储的文件。

我的节点/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
    }
  }
}

请问在SvelteKit中,如何在不创建与Node.js的依赖项的情况下完成此操作?根据SvelteKit端点文档

我们不与来自Node.js http模块或类似Express的框架中您可能熟悉的 req/res 对象进行交互,因为它们仅在某些平台上可用。相反,SvelteKit将返回的对象转换为您部署应用程序所需的任何内容。


1
你为什么想要移除节点依赖?端点在服务器上运行,对于所有适配器(除了静态适配器),它们都将在节点环境中运行。 - Stephane Vanraes
SvelteKit 的文档位于 https://kit.svelte.dev/docs#routing-endpoints 上,其中提到:“我们不使用你可能熟悉的来自 Node 的 http 模块或 Express 等框架的 req/res 对象,因为它们只在某些平台上可用。相反,SvelteKit 将返回的对象转换为部署应用程序所需的任何平台格式。” - nstuyvesant
是的,但这并不意味着您无法访问其他节点功能,只是SvelteKit将请求/响应部分抽象化了。 - Stephane Vanraes
由于在 get 方法中 res 不可用,想知道如何调用readStream.pipe(res)。 - nstuyvesant
只需将其管道传输到另一个临时变量中即可。 - Stephane Vanraes
只需调整上面的示例。获取“TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串类型或Buffer、ArrayBuffer或数组实例或类似数组的对象之一。收到未定义的” - nstuyvesant
1个回答

2

更新:SvelteKit已经修复了这个bug。以下是更新后的代码:

// 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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接