npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@grest-ts/http-file

v0.0.20

Published

HTTP file download codec for Grest framework

Readme

Part of the grest-ts framework. Documentation | All packages

@grest-ts/http-file

HTTP codecs for file uploads and downloads in the Grest framework. Handles multipart FormData encoding for uploads and binary response streaming for downloads — automatically, on both client and server.

In-memory files — when to use

Both GGFileUpload and GGFileDownload buffer the entire file in Node.js process memory. On upload, Busboy collects all chunks into a Buffer; on download, the full file is written to the response at once. This is simple and works great for prototyping, internal tools, and smaller applications.

For production systems handling large files or high throughput, consider uploading directly to an object store (S3, GCS, R2, etc.) — for example via presigned URLs — and passing only the resulting key/URL through your API. This keeps memory usage predictable and avoids OOM under load.

Quick Example

import { httpSchema } from "@grest-ts/http"
import { GGFileUpload, GGFileDownload } from "@grest-ts/http-file"
import { GGContractClass, IsObject, IsString, IsArray, VALIDATION_ERROR, SERVER_ERROR } from "@grest-ts/schema"
import { IsFile } from "@grest-ts/schema-file"

const FileApiContract = new GGContractClass("FileApi", {
    upload: {
        input: IsObject({ file: IsFile, description: IsString.orUndefined }),
        success: IsObject({ fileName: IsString, size: IsNumber }),
        errors: [VALIDATION_ERROR]
    },
    uploadBatch: {
        input: IsObject({
            files: IsArray(IsFile),
            metadata: IsObject({ tags: IsArray(IsString) })
        }),
        success: IsObject({ count: IsNumber }),
        errors: [VALIDATION_ERROR]
    },
    download: {
        input: IsObject({ id: IsString }),
        success: IsFile,
        errors: [SERVER_ERROR]
    }
})

export const FileApi = httpSchema(FileApiContract)
    .pathPrefix("api/files")
    .routes({
        upload:      GGFileUpload.POST("upload"),
        uploadBatch: GGFileUpload.POST("upload-batch"),
        download:    GGFileDownload.GET("download")
    })

That's it — the codecs handle multipart encoding, binary streaming, content headers, and filename preservation on both sides.

GGFileUpload

Codec for uploading files from client to server via multipart/form-data.

import { GGFileUpload } from "@grest-ts/http-file"

GGFileUpload.POST(path)

How it works

Client side: Splits the input into a FormData body:

  • A __json field containing all non-file data as JSON
  • Each file field appended as a binary part with its filename and MIME type
  • Content-Type header is not set explicitly — fetch() auto-detects the multipart boundary

Server side: Uses Busboy for streaming multipart parsing:

  • Extracts the __json field and parses it
  • Collects each file part into a GGFile via the schema's decodeFromRaw()
  • Reassembles the full input object with files at their original paths
  • Handles array fields (e.g. files.0, files.1) via wildcard matching

Usage rules

| Rule | Reason | |---|---| | Only POST is supported | Multipart upload requires a request body | | Input must contain at least one file field | Use GGRpc.POST for JSON-only routes | | Output is standard JSON | Use GGFileDownload for file responses |

Mixed file + JSON data

Files and JSON data are sent together in a single request. The codec automatically separates them:

const IsUploadRequest = IsObject({
    file: IsFile,                          // sent as binary part
    description: IsString.orUndefined,     // sent in __json
    tags: IsArray(IsString)                // sent in __json
})

File arrays

Arrays of files work naturally:

const IsBatchRequest = IsObject({
    files: IsArray(IsFile),                // each file sent as files.0, files.1, ...
    metadata: IsObject({ category: IsString })
})

GGFileDownload

Codec for downloading files from server to client as binary HTTP responses.

import { GGFileDownload } from "@grest-ts/http-file"

GGFileDownload.GET(path)
GGFileDownload.POST(path)

How it works

Server side: Sends the file as a binary response:

  • Content-Type set from the file's MIME type
  • Content-Length set from file size
  • Content-Disposition set with the filename (URL-encoded)
  • Error responses are sent as JSON with the appropriate status code

Client side: Parses the binary response:

  • Reads arrayBuffer() from the response
  • Extracts filename from Content-Disposition header
  • Creates a GGFile instance via the schema's decodeFromRaw()
  • JSON error responses are parsed normally

Usage rules

| Rule | Reason | |---|---| | GET or POST supported | GET for simple lookups, POST for complex queries | | Output must be a file schema (e.g. IsFile) | Use GGRpc.GET/POST for JSON responses | | Input must be JSON-only | File download routes accept JSON input, not file uploads |

GET vs POST downloads

.routes({
    // GET — parameters sent as query string
    downloadById: GGFileDownload.GET("download"),

    // POST — parameters sent as JSON body
    generateReport: GGFileDownload.POST("generate-report")
})

Use GET for simple key-based lookups. Use POST when the request body is complex.

Service Implementation

Services return GGFile for downloads and receive GGFile for uploads — no transport details leak into business logic:

import { GGFile } from "@grest-ts/schema-file"

class FileService implements IFileApi {
    async upload(request: { file: GGFile, description?: string }) {
        const bytes = await request.file.buffer()
        await storage.save(request.file.name, bytes)
        return { fileName: request.file.name, size: request.file.size }
    }

    async download(request: { id: string }): Promise<GGFile> {
        const data = await storage.load(request.id)
        return GGFile.fromBuffer(data.bytes, data.name, data.mimeType)
    }
}

Browser Support

The package has separate entry points for Node.js and browsers:

| Entry | Client | Server | |---|---|---| | Node.js (default) | Full support | Full support | | Browser (browser) | Full support | Throws error |

Browser builds only include client-side codecs (request building and response parsing). Server-side codecs (createForServer) throw an error in the browser since they depend on Node.js APIs (http.IncomingMessage, Busboy).

This is handled automatically by bundlers via the browser export condition — no configuration needed.

Path Parameters

Upload routes support path parameters:

.routes({
    uploadAvatar: GGFileUpload.POST("users/:userId/avatar")
})

// Client call:
await api.uploadAvatar({ userId: "123", avatar: file })
// → POST /api/files/users/123/avatar