Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

lbx-form-data

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lbx-form-data

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

  • 7.0.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
8
decreased by-11.11%
Maintainers
1
Weekly downloads
 
Created
Source

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

  • LbxFormData
  • Table of Contents
  • Usage

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.

More information about how to define the model for the data can be found below.

  • tempFolder: While resolving the request, all files are stored in a temporary folder. This is the path to that.
  • cleanup(): A method that will recursively delete the temporary folder, rendering any value data that references files useless.

The component also comes with a cron job that does this automatically, so forgetting to call this when you are finished dealing with the files shouldn't be a concern.

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.

Keywords

FAQs

Package last updated on 03 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc