Written by: Geoffrey Callaghan

Superstruct Tutorial

Superstruct Tutorial

Superstruct is a lightweight library for creating data structures and validating JavaScript objects against them. It’s useful for ensuring that data conforms to specific shapes or schemas. This tutorial will guide you through the basics of using Superstruct to define structures and validate data in JavaScript.

Step 1: Install Superstruct

You can install Superstruct via npm or yarn:

npm install superstruct
# or
yarn add superstruct

Step 2: Define Data Structures

Superstruct allows you to define data structures using a simple and expressive syntax. You can define structures for objects, arrays, primitives, and more.

  1. Define a Structure:
const { struct } = require('superstruct');

const User = struct({
  id: 'number',
  name: 'string',
  email: 'string',
});
  1. Define Nested Structures:
const Product = struct({
  id: 'number',
  name: 'string',
  price: 'number',
});

const Order = struct({
  id: 'number',
  customer: User,
  products: [Product],
});

Step 3: Validate Data

Once you’ve defined your structures, you can use them to validate data. Superstruct provides a validate function for this purpose.

  1. Validate Data:
const { validate } = require('superstruct');

const data = {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com',
};

const result = validate(data, User);

if (result[0]) {
  console.log('Data is valid:', data);
} else {
  console.error('Validation failed:', result[1]);
}

Step 4: Handle Validation Errors

When validation fails, Superstruct returns an array where the first element is a boolean indicating success or failure, and the second element is an error message or the validated data.

const data = {
  id: 1,
  name: 'John Doe',
  email: 123, // invalid email format
};

const result = validate(data, User);

if (result[0]) {
  console.log('Data is valid:', data);
} else {
  console.error('Validation failed:', result[1]);
}

Step 5: Custom Error Messages

You can also provide custom error messages for each field in your structure.

const User = struct({
  id: 'number',
  name: 'string',
  email: struct.union(['string', 'string'], {
    message: 'Email must be a valid string',
  }),
});

Step 6: Advanced Usage

Superstruct provides additional features for more complex validation scenarios.

  1. Conditional Validation:
const User = struct({
  id: 'number',
  name: 'string',
  email: 'string',
  role: struct.enum(['admin', 'user']),
  admin: struct.optional('boolean'),
});

const data = {
  id: 1,
  name: 'John Doe',
  email: 'john@example.com',
  role: 'admin',
};

const result = validate(data, User);

if (result[0]) {
  console.log('Data is valid:', data);
} else {
  console.error('Validation failed:', result[1]);
}
  1. Custom Validators:

You can define custom validators using the superstruct function:

const { superstruct } = require('superstruct');

const isEven = (value) => value % 2 === 0;

const schema = superstruct({
  types: {
    even: isEven,
  },
});

const EvenNumber = schema('even');

const data = 3;

const result = EvenNumber(data);

if (result[0]) {
  console.log('Data is valid:', data);
} else {
  console.error('Validation failed:', result[1]);
}

Conclusion

Superstruct is a versatile library for defining data structures and validating JavaScript objects against them. This tutorial covered the basics of defining structures, validating data, handling errors, and advanced usage scenarios. For more detailed documentation and examples, refer to the official Superstruct documentation.