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 🙏

© 2024 – Pkg Stats / Ryan Hefner

lbx-form-data

v7.0.0

Published

Library that parses inject multipart/form-data (eg. files) in your controller endpoints.

Downloads

173

Readme

LbxFormData

This package provides and registers a body parser for multipart/form-data requests. Uses multer under the hood.

It also provides validators for mimetype, fileSize and totalFileSize for Arrays of files.

Table of Contents

Usage

Setup

The minimum required code changes to use the library to its full extend is simply registering it in the application.ts:

import { LbxFormDataComponent } from 'lbx-form-data';

export class MyApplication extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
    constructor(options: ApplicationConfig = {}) {
        // ...
        this.component(LbxFormDataComponent);
        // ...
    }
}

This will add the body parser, all additonal validators aswell as the cron job for cleaning up temporary folders once a day.

Resolving requests

Just use the @requestBody decorator with the following configuration:

import { FormData } from 'lbx-form-data';

@requestBody({
    content: {
        // Documentation for model data is below
        'multipart/form-data': {}
    }
})
formData: FormData<TestFormDataModel>

This resolves the request to an FormData Wrapper Class, which consists of:

  • value: The request resolved to an TestFormDataModel object. If it's possible this will also parse strings as objects.

Model, Validation and OpenApi Specification

An example for a complex form data model with files and json data can be found below.

For file uploads you need to define type: 'string' and jsonSchema: { format: 'binary' }. This works for arrays aswell when defined on jsonSchema.items. The resolved type is File provided by the library.

In addition to the usual @property options, three new validators for files have been added:

  • mimetype: Provide an array of mimetypes to which the file or file array should be restricted.
  • fileSize: Provide the maximum amount of bytes a file or each file in an array might have. The library also provides a getBytes function to resolve kb, mb or gb to bytes.
  • totalFileSize: Provide the maximum amount of total file size of a file array in bytes.

Validators and file arrays

A little heads up: Both mimetype and fileSize validators work with arrays, but you can't set them on the items jsonSchema without using //@ts-ignore. If you are okay with using that then everything works perfectly fine.

If you don't want to use @ts-ignore you can also provide the validators directly on the arrays jsonSchema instead of items.jsonSchema. But in that case the error does not show which file was too large or of the wrong type.

Example

import { File, getBytes } from 'lbx-form-data';

@model()
class Test extends Model {
    @property({
        type: 'string',
        required: true
    })
    name: string;

    @property({
        type: 'number',
        required: true
    })
    value: number;
}

@model()
class TestFormDataModel extends Model {
    @property({
        type: 'string',
        jsonSchema: {
            format: 'binary'
            fileSize: getBytes(1.3, 'kb')
        },
        required: true
    })
    singleFile: File;

    @property({
        type: 'array',
        jsonSchema: {
            items: {
                type: 'string',
                format: 'binary'
            },
            mimetype: ['application/pdf'],
            fileSize: getBytes(6, 'kb'),
            totalFileSize: getBytes(100, 'kb')
        }
    })
    multipleFiles: File[];

    @property({
        type: Test,
        required: true
    })
    body: Test;
}

Cleanup/Cron Job

This library uses multer for resolving files from the multipart/form-data request.

It is recommended to cache files in a temporary folder to not run into memory limits, therefore a diskStorage is used. To clean this up, you can either call cleanup() on the parsed FormData object when you are finished handling the files or let the cron job handle it.

The cron job is automatically registered and started when you boot your application. To not delete files that are currently being used, a file with a createdAt timestamp is generated in the temp folder for each request. The cron job only deletes folders where the createdAt timestamp is at least 24 hours ago.