Skip to content

Validation().dataMapper()

Sets a data mapper function to map request body values with form fields.

Syntax

Validation().dataMapper(mappingFunction)

Parameters

  • mappingFunction
    A function to add that will be called with the following arguments:

Return value

The Validation object.

Exceptions

  • If anything other than a function is passed in the corresponding error will be thrown.

  • If invoked on a Validation which was not created with the Validation.profile() method, throws the corresponding error.

Description

The main purpose of this method is to provide a way of mapping a request object’s body with form fields specified in the Validation.profile() method in cases when they do not correspond to each other when a Validation is used as a middleware function.

Examples

Validating file metadata before uploading to S3 storage

In this example the Validation().dataMapper() method is used to map the values passed as URL search parameters to the form fields created with the Validation.profile() method.

The project can be downloaded here.

  • Directorypublic
    • Directorylibs
      • isomorphic-validation.mjs the library file is copied and imported from here to be available on the client side without using a module bundler
    • index.html
    • index.js the main frontend script
    • validation.js file size and type validation code
  • config.js a config for S3 storage
  • index.js the main backend script
  • repository.js a mock repository API
import express from 'express';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { bucketName, endpoint, accessKeyId, secretAccessKey } from "./config.js";
import uploadValidation from './public/validation.js';
import * as repository from './repository.js';
const s3client = new S3Client({
region: 'REGION', endpoint, credentials: { accessKeyId, secretAccessKey },
});
const app = express();
app.use(express.static('public'));
uploadValidation.dataMapper((req, form) => {
Object.assign(form.file.files[0], req.query);
});
app.get('/get-signed-url', uploadValidation, async (req, res, next) => {
if (req.validationResult.isValid) {
const { type, size } = req.query;
// create a file record in the database
const id = await repository.create({ type, size, uploaded: false });
const putObjCmd = new PutObjectCommand({
Bucket: bucketName,
Key: id,
ContentType: type,
ContentLength: size,
});
res.json({
url: await getSignedUrl(s3client, putObjCmd, { expiresIn: 60 }),
id,
});
}
else {
res.json({ error: 'The file is inappropriate.' });
}
});
app.get('/image-uploaded/:id', async (req, res) => {
// mark the file record as permanent (successfully uploaded to the s3 storage)
const { id } = req.params;
const ok = await repository.update(id, { uploaded: true });
res.json(ok);
});
app.listen(8080, () => { console.log('listening port 8080...')});