# Introduction

## A simple schema/attributes library built on top of modern JavaScript

## [![npm](https://img.shields.io/npm/v/structure.svg?style=flat)](https://www.npmjs.com/package/structure) [![Build Status](https://travis-ci.org/talyssonoc/structure.svg?branch=master)](https://travis-ci.org/talyssonoc/structure) [![Coverage Status](https://coveralls.io/repos/github/talyssonoc/structure/badge.svg?branch=master)](https://coveralls.io/github/talyssonoc/structure?branch=master) [![Code Climate](https://codeclimate.com/github/talyssonoc/structure/badges/gpa.svg)](https://codeclimate.com/github/talyssonoc/structure) [![JS.ORG](https://img.shields.io/badge/js.org-structure-ffb400.svg?style=flat)](https://js.org/)

Structure provides a simple interface which allows you to add attributes to your ES6 classes based on a schema, with validations and type coercion.

## Use cases

You can use Structure for a lot of different cases, including:

* Domain entities and value objects
* Model business rules
* Validation and coercion of request data
* Map pure objects and JSON to your application classes
* Add attributes to classes that you can't change the class hierarchy

What Structure is **not**:

* It's not a database abstraction
* It's not a Model of a MVC framework
* It's not an attempt to simulate classic inheritance in JavaScript

## [Documentation](https://structure.js.org/)

## Example usage

For each attribute on your schema, a getter and a setter will be created into the given class. It'll also auto-assign those attributes passed to the constructor.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: String,
  age: {
    type: Number,
    default: 18,
  },
  birthday: Date,
})(
  class User {
    greet() {
      return `Hello ${this.name}`;
    }
  }
);

/* The attributes "wraps" the Class, still providing access to its methods: */

const user = new User({
  name: 'John Foo',
});

user.name; // 'John Foo'
user.greet(); // 'Hello John Foo'
```

## [Contributing](/contributing)

## [LICENSE](/license)


# Schema concept

The schema is an object responsible to map the attributes Structure should handle, it is the parameter of the `attributes` function.

```javascript
attributes({
  name: String,
  age: Number,
})(class User {});
```

There are two ways to declare an attribute of the schema, the **shorthand attribute definition** and the **complete attribute definition**.


# Shorthand and complete attribute definition

## Shorthand attribute definition

The shorthand is a pair of `propertyName: Type` key/value like this:

```javascript
const User = attributes({
  name: String,
  brithday: Date,
})(
  class User {
    generateRandomBook() {
      return '...';
    }
  }
);
```

## Complete attribute definition

The complete definition allows you to declare additional info for the attribute. **For Array types it's required to use the complete attribute definition because you&#x20;*****must*****&#x20;specify the `itemType`**.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous',
  },
  cars: {
    type: Array,
    itemType: String,
    default: ['Golf', 'Polo'],
  },
  book: {
    type: String,
    default: (instance) => instance.generateRandomBook(),
  },
})(
  class User {
    generateRandomBook() {
      return '...';
    }
  }
);
```

### default

The **default** of an attribute will be used if no value was provided for the specific attribute at construction time.

You can also use a function which receives the instance as a parameter in order to provide the default. The operation must be synchronous and the function will called after all the other attributes are already assigned, thus, you can use the other attributes of your class to compose a default value.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous', // static default value
  },
  greeting: {
    type: String,
    default: (instance) => instance.greeting(), // dynamic default value
  },
})(
  class User {
    greeting() {
      return `Hello ${this.name}`;
    }
  }
);
```

Please note that initializing an attribute with undefined will make it fallback to the default value while instantiating the structure, but it will not fallback when assigning the attribute after the structure is already constructed.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous', // static default value
  },
})(class User {});

const firstUser = new User({ name: undefined });
firstUser.name; // 'Anonymous' =>  fallbacks to default value

const secondUser = new User({ name: 'Some name' });

secondUser.name = undefined;
secondUser.name; // undefined => does not fallback to default value
```

### itemType

The **itemType** of an attribute is used to validate and coerce the type of each item from the attribute, like when the attribute type is `Array` or some class that extends `Array`.

* Please refer to [Validation](/validation) in order to check a bit more on validation properties.

## Type concept

Each attribute needs a **type** definition, that's how Structure validates and coerces the attribute's value. It can be divided into three categories (as in right now):

* Primitives (Number, String, Boolean)
* Classes (Date, Object, regular Classes and Structure classes as well)
* Array/Array-like (Array, extended Array)


# Circular reference

Sometimes we may need to have a type reference itself in its attributes, or have two types that reference eachother in separate files, it can be a complication because it's not possible to do this using the type definitions like we did before. For cases like this we can use a feature called "dynamic types".

When using dynamic types you can pass a string instead of the type itself in the type definition, this string will contain the type **identifier**, and then pass an object as the *second* parameter of the `attributes` function with a key `dynamics` where the concrete type for each identifier is declared:

```javascript
/*
 * User.js
 */
const User = attributes(
  {
    name: String,
    friends: {
      type: Array,
      itemType: 'User', // << identifier
    },
    favoriteBook: {
      type: 'BookStructure', // << identifier
      required: true,
    },
    books: {
      type: 'BooksCollection', // << identifier
      itemType: String,
    },
  },
  {
    dynamics: {
      /* dynamic types for each identifier */
      User: () => User,
      BookStructure: () => require('./Book'),
      BooksCollection: () => require('./BooksCollection'),
    },
  }
)(class User {});

module.exports = User;

/*
 * Book.js
 */
const Book = attributes(
  {
    name: String,
    owner: 'User', // << dynamic type with inferred identifier
    nextBook: 'BookStructure', // << dynamic type with custom identifier
  },
  {
    identifier: 'BookStructure', // << custom identifier
    dynamics: {
      /* dynamic types for each identifier */
      User: () => require('./User'),
      BookStructure: () => Book,
    },
  }
)(class Book {});

module.exports = Book;
```

If you're using `import` instead of `require` (thus having to import the dynamic value in the top-level of the file), go to the [With ES Modules](/schema-concept/circular-references-and-dynamic-types#with-es-modules) section of this page.

## Dynamic type identifier

The type's identifier has to be same everywhere it's used, and can be defined in two ways:

### Inferred identifier

The identifier can be inferred based on the class that is wrapped by the `attributes` function. In backend scenarios this will be the most common case:

```javascript
const User = attributes(
  {
    name: String,
    bestFriend: 'User', // [A] type with inferred identifier
  },
  {
    dynamics: {
      User: () => User, // [B] inferred identifier concrete type
    },
  }
)(
  class User {
    //   ⬑-- the name of this class is the identifier
    // so if we change this name to UserEntity, we'll have to change
    // both [A] and [B] to use the string 'UserEntity' instead of 'User'
  }
);
```

### Custom identifier

If for some reason you can't rely on the class name, be it because you're using a compiler that strips class names or creates a dynamic one, you can explicitly set an indentifier.

To do that, in the second argument of the `attributes` function (e.g. the options) you should add a `identifier` key and set it to be the string with the type's identifier and then use that custom value everywhere this type is dynamically needed:

```javascript
const User = attributes(
  {
    name: String,
    bestFriend: 'UserEntity', // << type with custom identifier
  },
  {
    identifier: 'UserEntity', // << custom identifier
    dynamics: {
      // ⬐--- custom identifier concrete type
      UserEntity: () => User,
    },
  }
)(class User {});
```

## Concrete type definition inside `dynamics`

For the cases where the dynamic type is in a different file, it's important that the actual needs type to be resolved **inside** the function with the identifier. Let's break it down in two cases:

### With CommonJS modules

When using CommonJS modules you have two possibilities:

1. Putting the `require` call directly inside the concrete type resolution function:

```javascript
const Book = attributes(
  {
    name: String,
    owner: 'User',
    nextBook: 'BookStructure',
  },
  {
    identifier: 'BookStructure',
    dynamics: {
      User: () => require('./User'), // << like this
      BookStructure: () => Book,
    },
  }
)(class Book {});

module.exports = Book;
```

1. Exporting an **object** containing your other structure (instead of exporting the structure itself) and only access it inside the concrete type resolution function:

```javascript
/*
 * User.js
 */
const BookModule = require('./Book');

const User = attributes(
  {
    name: String,
    favoriteBook: {
      type: 'Book',
      required: true,
    },
  },
  {
    dynamics: {
      User: () => User,
      Book: () => BookModule.Book,
    },
  }
)(class User {});

exports.User = User;

/*
 * Book.js
 */
const UserModule = require('./User');

const Book = attributes(
  {
    name: String,
    owner: 'User',
  },
  {
    dynamics: {
      User: () => UserModule.User,
      Book: () => Book,
    },
  }
)(class Book {});

exports.Book = Book;
```

### With ES Modules

When using ES Modules you have a single possibility, which is importing the other structure from the top-level of your file and then returning it from the concrete type resolution function. It's important to note that this **only** works with ES Modules, if you're using CommonJS, check the [With CommonJS modules](/schema-concept/circular-references-and-dynamic-types#with-commonjs-modules) section.

```javascript
/*
 * User.js
 */
import Book from './Book';

const User = attributes(
  {
    name: String,
    favoriteBook: {
      type: 'Book',
      required: true,
    },
  },
  {
    dynamics: {
      User: () => User,
      Book: () => Book,
    },
  }
)(class User {});

export default User;

/*
 * Book.js
 */
import User from './User';

const Book = attributes(
  {
    name: String,
    owner: 'User',
  },
  {
    dynamics: {
      User: () => User,
      Book: () => Book,
    },
  }
)(class Book {});

export default Book;
```


# Nullable attributes

You can change the way an attribute is treated when the value `null` is assigned to it by using the `nullable` option with the value `true`, this would affect the way the attribute is defaulted, coerced, validated and serialized.

If you do not set the `nullable` option it will default to `false` and automatically make your attribute **non-nullable**.

## Nullability and `default` option

Non-nullable attributes with the value `null` will fallback to the value set as default the same way `undefined` does. But if the attribute is nullable, it will **only** fallback to the default if its value is `undefined`.

```javascript
const User = attributes({
  name: {
    // automatically non-nullable
    type: String,
    default: 'Some string',
  },
  nickname: {
    type: String,
    nullable: false,
    default: 'Some other string',
  },
})(class User {});

const userA = new User({ name: null, nickname: null });
userA.attributes; // { name: 'Some string', nickname: null }

const userB = new User({ name: null, nickname: undefined });
userB.attributes; // { name: 'Some string', nickname: 'Some other string' }
```

## Coercion

Non-nullable values will fallback to their null-equivalent values. More details about it can be found at the [coercion](https://github.com/talyssonoc/structure/tree/8539a498ca15b08eaa0bb93f34b94f2cf3bc499e/docs/schema-concept/coercion/README.md) section. Nullable attributes will remain `null` as described in the section above.

```javascript
/*
 * User.js
 */
const User = attributes({
  name: {
    type: String,
    nullable: true,
  },
  nickname: {
    // automatically non-nullable
    type: String,
    empty: true,
  },
  age: Number, // << automatically non-nullable
  active: Boolean, // << automatically non-nullable
  createdAt: Date, // << automatically non-nullable
})(class User {});

const user = new User({
  name: null,
  nickname: null,
  age: null,
  active: null,
  createdAt: null,
});

// Only non-nullable values are coerced to their null-equivalent values
user.attributes; // { name: null, nickname: '', age: 0, active: false, createdAt: 1970-01-01T00:00:00.000Z }
user.validate(); // { valid: true }
```

### Nullable optional attributes

When you set an optional attribute to be **nullable** you are choosing not to assign a default value for it when instantiating your structure passing `null` as the value of this attribute, so the actual value will be `null` and will be considered valid.

```javascript
/*
 * User.js
 */
const User = attributes({
  name: {
    type: String,
    nullable: true,
  },
})(class User {});

const user = new User({
  name: null,
});

user.attributes; // { name: null }
user.validate(); // { valid: true }
```

### Nullable required attributes

We consider that when an attribute is **required** there should be some value assigned to it even if it's `undefined`, `null` or any other value. It means that coercion will never assign a **default** value to **required** attributes even if **nullable** option is **false**.

```javascript
/*
 * User.js
 */
const User = attributes({
  name: {
    type: String,
    required: true,
    nullable: false, // non-nullable required attribute
  },
})(class User {});

const user = new User({
  name: null,
});

user.attributes; // { name: null }
user.validate(); // { valid: false }
```

But notice that you can choose to allow **null** values on **required** attributes which will cause the validation to return **true**.

```javascript
/*
 * User.js
 */
const User = attributes({
  name: {
    type: String,
    required: true,
    nullable: true,
  },
})(class User {});

const user = new User({
  name: null,
});

user.attributes; // { name: null }
user.validate(); // { valid: true }
```

## Nullability and serialization

Usually an attribute with the value **undefined** or **null** is not included when you serialize your structure. But when it is **nullable** and its value is `null`, this attribute is going to be returned in your serialized schema.

```javascript
const User = attributes({
  name: {
    type: String,
    nullable: false,
  },
  nickname: {
    type: String,
    nullable: true,
  },
})(class User {});

const user = new User({ name: undefined, nickname: null });
user.toJSON(); // { nickname: null }
```

**Important:**

* Notice that by not using the `nullable` option the **default** value for **String** is an empty string, which means that you need to accept empty strings to make your schema valid.


# Custom setters and getters

Sometimes it may be necessary to have custom setters and/or getters for some attributes. Structure allows you to do that using native JavaScript setters and getters. It will even support coercion.

It's important to notice that you **should not** try to access the attribute directly inside its getter or to set it directly inside its setter because it will cause infinite recursion, this is default JavaScript behavior. To access an attribute value inside its getter you should use `this.get(attributeName)`, and to set the value of an attribute a setter you should use `this.set(attributeName, attributeValue)`:

```javascript
const User = attributes({
  firstName: String,
  lastName: String,
  age: Number,
})(
  class User {
    get firstName() {
      return `-> ${this.get('firstName')}`;
    }

    set lastName(newLastname) {
      return this.set('lastName', `Mac${newLastName}`);
    }

    get age() {
      // do NOT do that. Instead, use this.get and this.set inside getters and setters
      return this.age * 1000;
    }

    // this is NOT an attribute, just a normal getter
    get fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  }
);

const user = new User({ firstName: 'Connor', lastName: 'Leod' });

user.firstName; // -> Connor
user.lastName; // MacLeod
user.fullName; // -> Connor MacLeod
```

## Inheritance

Custom setters and getters are also inherited, be your superclass a pure JavaScript class or another structure:

```javascript
class Person {
  // If Person was a structure instead of a pure class, that would work too
  get name() {
    return 'The person';
  }
}

const User = attributes({
  name: String,
})(class User extends Person {});

const user = new User({ name: 'Will not be used' });

user.name; // -> The person
```

**Important**

JavaScript nativelly won't let you inherit only one of the accessors (the getter or the setter) if you define the other accessor in a subclass:

```javascript
class Person {
  get name() {
    return 'Person';
  }
}

class User extends Person {
  set name(newName) {
    this._name = newName;
  }
}

const user = new Person();
user.name = 'The user';
user.name; // -> The user
```

It happens because *once you define one of the accessors in a subclass*, all the accessors for the same attribute inherited from the superclass will be ignored.

While it's a weird behavior, Structure will follow the same functionality so the Structure classes inheritance work the same way of pure JavaScript classes, avoiding inconsistencies.


# Coercion

Structure does type coercion based on the declared [schema](/schema-concept), let's break it into 3 categories:

* [Primitive type coercion](/coercion/primitive-type-coercion)
* [Arrays coercion](/coercion/arrays-and-array-subclasses)
* [Generic coercion](/coercion/generic-coercion)

## Observations

Structure **never** coerces the following scenarios:

* value is `undefined`;
* value is `null` when `nullable` option is enabled;
* value is already of the declared type (except for arrays, we'll talk more about this soon).


# Primitive type coercion

It's said to be primitive type coercion when it tries to coerce values to `String`, `Number` or `Boolean` types.

For those types we basically use the type as a function (without using `new`), with a subtle difference: When coercing `null` to `String`, it'll coerce to empty string instead of the string `'null'` (unless when the attribute is [nullable](/schema-concept/nullable-attributes)). For example:

```javascript
const User = attributes({
  name: String,
  age: Number,
  isAdmin: Boolean,
})(class User {});

const userOne = new User({
  name: 'Foo Bar',
  age: 50,
  isAdmin: true,
});

userOne.name; // 'Foo Bar' => no coercion was done
userOne.age; // 50 => no coercion was done
userOne.isAdmin; // true => no coercion was done

const userTwo = new User({
  name: null,
  age: '100',
  isAdmin: undefined,
});

userTwo.name; // '' => coerced `null` to empty string
userTwo.age; // 100 => coerced string to number
userTwo.isAdmin; // undefined => it'll never coerce `undefined`
```


# Arrays coercion

It's also possible to coerce values to `Array` or some other class that extends `Array`. On these circumstances Structure will use the `itemType` value of the attribute definition on the schema to coerce the items as well. Note that, when coercing arrays, it'll always create a new instance of the type and then push each item of the passed value to the new instance:

```javascript
class BooksCollection extends Array {}

const Library = attributes({
  books: {
    type: BooksCollection,
    itemType: String,
  },
  users: {
    type: Array,
    itemType: String,
  },
})(class Library {});

const libraryOne = new Library({
  books: ['Brave New World'],
  users: ['John', 1],
});

libraryOne.books; // BooksCollection ['Brave New World'] => coerced the array to BooksCollection
libraryOne.users; // ['John', '1'] => new instance of Array with coerced items
```

The passed raw value have to be non-null and have a `length` attribute or implement the `Symbol.iterator` method, otherwise it'll fail to coerce and throw a `TypeError`.

## Observations

Structure only does array **items** coercion during instantiation, so mutating an array (using push, for example) won't coerce the new item:

```javascript
const Library = attributes({
  books: {
    type: Array,
    itemType: String,
  },
})(class Library {});

const library = new Library({
  books: [1984],
});

library.books; // ['1984'] => coerced number to string

library.books.push(42);

library.books; // ['1984', 42] => new item was not coerced
```


# Generic coercion

If the declared type is not a primitive nor Array (or an array subclass) it'll do generic coercion. When generic coercing a value, Structure will just instantiate the declared type (using `new`) passing the raw value as the parameter (only if the raw value isn't of the declared type already).

```javascript
class Location {
  constructor({ x, y }) {
    this.x = x;
    this.y = y;
  }
}

const User = attributes({
  location: Location,
})(class User {});

const userOne = new User({
  location: new Location({ x: 1, y: 2 }),
});

userOne.location; // Location { x: 1, y: 2 } => no coercion was done

const userTwo = new User({
  location: { x: 3, y: 4 },
});

userTwo.location; // Location { x: 3, y: 4 } => coerced plain object to Location
```

Coercion to `Date` type enters in this same category, so if you have an attribute of the type `Date`, it'll use `new Date(<raw value>)` to coerce it. For more info about how this coercion works check the cases for `value` and `dateString` parameters on [Date documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date).


# Recursive coercion

Structure also does recursive coercion so, if your declared type is Array or other Structure, the items/attributes of the raw value will be coerced as well:

```javascript
class BooksCollection extends Array {}

const Book = attributes({
  name: String,
})(class Book {});

const User = attributes({
  favoriteBook: Book,
  books: {
    type: BooksCollection,
    itemType: Book,
  },
})(class User {});

const user = new User({
  favoriteBook: { name: 'The Silmarillion' },
  books: [{ name: '1984' }],
});

user.favoriteBook; // Book { name: 'The Silmarillion' } => coerced plain object to Book
user.books; // BooksCollection [ Book { name: '1984' } ] => coerced array to BooksCollection and plain object to Book
```


# Disabling coercion

You can disable coercion for a whole structure or for attributes individually using the `coercion` option in the schema and attribute options, respectively. Notice that it will cause validation to fail when the passed value is not of the expected value:

## Disabling for the whole structure

```javascript
const User = attributes(
  {
    name: String,
    age: Number,
  },
  {
    coercion: false,
  }
)(class User {});

const user = new User({ name: 123, age: '42' });

user.name; // 123
user.age; // '42'

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"name" must be a string', path: ['name'] },
  { message: '"age" must be a number', path: ['age'] }
]
*/
```

## Disabling for specific attributes

```javascript
const User = attributes({
  name: { type: String, coercion: false },
  age: Number,
})(class User {});

const user = new User({ name: 123, age: '42' });

user.name; // 123
user.age; // 42

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"name" must be a string', path: ['name'] }
]
*/
```

## Overwritting structure option with attribute option

If you define the `coercion` option both for the structure *and* for an attribute, the structure one will apply for the whole schema except the specific attributes that overwrite it:

```javascript
const User = attributes(
  {
    name: { type: String, coercion: true },
    age: Number,
  },
  {
    coercion: false,
  }
)(class User {});

const user = new User({ name: 123, age: '42' });

user.name; // '123'
user.age; // '42'

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"age" must be a number', path: ['age'] }
]
*/
```


# Validation

A `validate()` method will be added to the prototype of structures, this method will validate the structure based on its schema. The method will return an object with the property `valid` (with the value `true` if it's valid, and `false` if invalid). If `valid` is `false` the returned object will also have a property `errors`, with an array of validation errors.

Validations require you to use the complete attribute definition:

```javascript
const User = attributes({
  name: {
    type: String,
    minLength: 10,
  },
  age: {
    type: Number,
    required: true,
  },
})(class User {});

const user = new User({
  name: 'John',
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"name" length must be at least 10 characters long', path: ['name'] },
  { message: '"age" is required', path: ['age'] }
]
*/

const validUser = new User({
  name: 'This is my name',
  age: 25,
});

const validation = validUser.validate();

validation.valid; // true
validation.errors; // undefined, because `valid` is true
```

Structure has a set of built-in validations built on top of the awesome [joi](https://www.npmjs.com/package/@hapi/joi) package:

**Observations**

Validations marked with **\*** accept a value, an [attribute reference](/validation/attribute-reference), or an array of values and attribute references mixed.

Validations marked with **\*\*** accept a value or an [attribute reference](/validation/attribute-reference).


# String validations

* `required`: can't be undefined (default: `false`)
* `empty`: accepts empty string (default: `false`)
* `equal`: **\*** equal to passed value
* `minLength`: can't be shorter than passed value
* `maxLength`: can't be longer than passed value
* `exactLength`: length must be exactly the passed value
* `regex`: matches the passed regex
* `alphanumeric`: composed only by alphabetical and numeric characters
* `lowerCase`: all characters must be lower cased
* `upperCase`: all characters must be upper cased
* `email`: is a valid email (default: `false`)
* `nullable`: accepts null (default: `false`)
* `guid`: is a valid guid. You can pass a boolean or the [options object accepted by Joi](https://hapi.dev/module/joi/api/?v=16.1.8#stringguid---aliases-uuid) (default: `false`)

```javascript
const User = attributes({
  id: {
    type: String,
    guid: true,
  },
  token: {
    type: String,
    guid: {
      version: ['uuidv4'],
    },
  },
  initials: {
    type: String,
    upperCase: true,
    maxLength: 4,
  },
  gender: {
    type: String,
    nullable: true,
  },
  password: String,
  passwordConfirmation: {
    type: String,
    equal: { attr: 'password' },
  },
  greet: {
    type: String,
    required: true,
    equal: ['Mr', 'Ms', 'Mrs', 'Miss', { attr: 'greetDesc' }],
  },
  greetDesc: String,
})(
  class User {
    getFullGreet() {
      return `${this.greet} ${this.initials}`;
    }
  }
);
```


# Number validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `integer`: must be an integer (default: `false`)
* `precision`: maximum number of decimal places
* `positive`: must be positive (default: `false`)
* `negative`: must be negative (default: `false`)
* `multiple`: must be a multiple of the passed value
* `min`: **\*\*** minimum valid value (works like the `>=` operator)
* `greater`: **\*\*** must be greater than passed value (works like the `>` operator)
* `max`: **\*\*** maximum valid value (works like the `<=` operator)
* `less`: **\*\*** must be smaller than passed value (works like the `<` operator)
* `nullable`: accepts null (default: `false`)

```javascript
const Pool = attributes({
  depth: {
    type: Number,
    positive: true
  },
  width: {
    type: Number,
    min: { attr: 'depth' }
  },
  length: {
    type: Number,
    greater: { attr: 'width' }
  },
  capacity: {
    type: Number,
    nullable: true
  }
})(class Pool {
  getVolume() {
    return this.depth * this.width * this.length;
  }
});
```


# Boolean validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `nullable`: accepts null (default: `false`)

```javascript
const User = attributes({
  isAdmin: {
    type: Boolean,
    required: true
  },
  hasAcceptedTerms: {
    type: Boolean,
    nullable: true
  }
})(class User { });
```


# Date validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `min`: **\*\*** must be after passed date
* `max` **\*\*** must be before passed date
* `nullable`: accepts null (default: `false`)

```javascript
const Product = attributes({
  fabricationDate: {
    type: Date,
    default: () => Date.now()
  },
  expirationDate: {
    type: Date,
    min: { attr: 'fabricationDate' }
  },
  createdAt: {
    type: Date,
    nullable: true
  }
})(class Product { });
```


# Array validations

* `required`: can't be undefined (default: `false`)
* `sparse`: can have undefined items (default: `true`)
* `unique`: can't have duplicate items (default: `false`)
* `minLength`: minimum quantity of items
* `maxLength`: maximum quantity of items
* `exactLength`: exact quantity of items

```javascript
const Group = attributes({
  members: {
    type: Array,
    itemType: String,
    minLength: 2,
    maxLength: 5,
    sparse: false,
    unique: true
  },
  leaders: {
    type: Array,
    itemType: String,
    minLength: 1,
    maxLength: { attr: 'members' }
  }
})
```


# Attribute reference

You can reference attributes for some validations so the value of the referenced attribute will be used for the comparison:

```javascript
const User = attributes({
  name: String,
  password: String,
  passwordConfirmation: {
    type: String,
    equal: { attr: 'password' },
  },
})(class User {});

const user = new User({
  name: 'Gandalf',
  password: 'safestpasswordever',
  passwordConfirmation: 'notthatsafetho',
});

const { valid, errors } = user.validate();

valid; // false
errors; /* [
  {
    message: '"passwordConfirmation" must be one of [ref:password]',
    path: ['passwordConfirmation']
  }
]
*/
```


# Nested validations

Structure will validate nested values, including array items validations and nested structures.

```javascript
const Book = attributes({
  name: {
    type: String,
    required: true,
  },
})(class Book {});

const User = attributes({
  initials: {
    type: String,
    minLength: 2,
  },
  favoriteBook: Book,
  books: {
    type: Array,
    itemType: Book,
  },
})(class User {});

const user = new User({
  initials: 'A',
  favoriteBook: new Book(),
  books: [new Book()],
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"initials" length must be at least 2 characters long', path: ['initials'] },
  { message: '"favoriteBook.name" is required', path: ['favoriteBook', 'name'] },
  { message: '"books[0].name" is required', path: ['books', 0, 'name'] }
]
*/
```


# Validate raw data

In addition to the *instance* `validate()` method, Structure also adds a *static* `validate()` to your structure classes that receives a *raw object* or a *structure instance* as parameter and has the same return type of the [normal validation](/validation):

```javascript
const User = attributes({
  name: {
    type: String,
    minLength: 10,
  },
  age: {
    type: Number,
    required: true,
  },
})(class User {});

// Using a raw object
const rawData = {
  name: 'John',
};

const { valid, errors } = User.validate(rawData);

valid; // false
errors; /*
[
  { message: '"name" length must be at least 10 characters long', path: ['name'] },
  { message: '"age" is required', path: ['age'] }
]
*/

// Using a structure instance
const user = new User({
  name: 'Some long name',
});

const validation = User.validate(user);

validation.valid; // false
validation.errors; /*
[
  { message: '"age" is required', path: ['age'] }
]
*/
```


# Strict mode

To instantiate a structure that automatically throws an error if that is invalid, you can use the buildStrict function.

```javascript
const { attributes } = require('structure');
const User = attributes({
  name: {
    type: String,
    required: true,
  },
  age: Number,
})(class User {});

const user = User.buildStrict({
  age: 'Twenty',
});

// Error: Invalid Attributes
// details: [
//   { message: '"name" is required', path: ['name'] },
//   { message: '"age" must be a number', path: ['age'] }
// ]
```

## Custom error

Normally `buildStrict` will throw a default `Error` when attributes are invalid but you can customize the error class that will be used passing a `strictValidationErrorClass` to the *second* parameter of the `attributes` function.

The value of `strictValidationErrorClass` should be a class that accepts an array of erros in the constructor.

```javascript
const { attributes } = require('structure');

class InvalidBookError extends Error {
  constructor(errors) {
    super('Wait, this book is not right');
    this.code = 'INVALID_BOOK';
    this.errors = errors;
  }
}

const Book = attributes(
  {
    name: {
      type: String,
      required: true,
    },
    year: Number,
  },
  {
    strictValidationErrorClass: InvalidBookError,
  }
)(class Book {});

const book = Book.buildStrict({
  year: 'Twenty',
});

// InvalidBookError: Wait, this book is not right
// code: 'INVALID_BOOK'
// errors: [
//   { message: '"name" is required', path: ['name'] },
//   { message: '"year" must be a number', path: ['year'] }
// ]
```


# Cloning an instance

Structure adds a method `#clone` in order to be able to create a **shallow** copy of an instance. This methods accepts an optional overwrite object that permits you to overwrite some attributes of the copy.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: String,
})(class User {});

const user = new User({
  name: 'Me',
});

const cloneUserWithNoOverwrite = user.clone(); // User { name: 'Me }

const cloneWithOverwrite = user.clone({ name: 'Myself' }); // User { name: 'Myself' }
```

If the structure has a nested structure inside of it, the `#clone` method **will not** clone it but just point the new instance to the old value of the nested attribute.

```javascript
const { attributes } = require('structure');

const Book = attributes({
  name: String,
})(class Book {});

const User = attributes({
  name: String,
  favoriteBook: Book,
})(class User {});

const user = new User({
  name: 'Me',
  favoriteBook: new Book({ name: 'The Silmarillion' }),
});

const cloneUserWithNoOverwrite = user.clone();
cloneUserWithNoOverwrite.favoriteBook === user.favoriteBook; // true, it was not cloned

const cloneWithOverwrite = user.clone({
  favoriteBook: { name: 'The Lord of the Rings' },
});
cloneWithOverwrite.favoriteBook === user.favoriteBook; // false, it was **replaced** with the new value
cloneWithOverwrite.favoriteBook; // Book { name: 'The Lord of the Rings' }
```

## Strict mode

When cloning an instance, you can clone it in [strict mode](/strict-mode) as well, so if the resulting clone is invalid it throws an error. To do that, pass a second argument to the `#clone` method with the option `strict` as `true`.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: {
    type: String,
    required: true,
  },
  age: Number,
})(class User {});

const user = new User({
  name: 'Me',
});

const clonedUser = user.clone(
  { name: null },
  { strict: true } // strict mode option
);

// Error: Invalid Attributes
// details: [
//   { message: '"name" is required', path: ['name'] }
// ]
```


# Serialization

It's possible to obtain a serialized object of a Structure using the method `toJSON()`. This method is also compliant with the [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) specification, so you can use it to serialize your object too.

**Important:**

* Be aware that `toJSON()` will return an object, not the JSON in form of a string like `JSON.stringify()` does
* Refer to the [Date#toJSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) specification to see how dates will be serialized by `JSON.stringify`
* Refer to [Dealing with nullable attributes](/schema-concept/nullable-attributes#nullability-and-serialization) to check how `nullables` are going to be returned on **Serialization**

```javascript
const Book = attributes({
  name: String
})(class Book { });

const User = attributes({
  name: String,
  birth: Date,
  books: {
    type: Array,
    itemType: Book
  }
})(class User { });

const user = new User({
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    new Book({ name: 'The name of the wind' }),
    new Book({ name: 'Stonehenge' })
  ]
});

user.toJSON(); /* {
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    { name: 'The name of the wind' },
    { name: 'Stonehenge' }
  ]
}
*/

JSON.stringify(user)); // {"name":"John Something","birth":"1990-10-10T03:00:00.000Z","books":[{"name":"The name of the wind"},{"name":"Stonehenge"}]}
```


# Testing

If you use Jest, Structure has a Jest extension called [`jest-structure`](https://www.npmjs.com/package/jest-structure) that provides assertions to make it easy to test intances.

## Installation

jest-structure is available in npm, so you can install it with npm or yarn as a development dependency:

```bash
npm install --save-dev jest-structure

# or

yarn --dev add jest-structure
```

## Setup

After installing, you need to tell Jest to use jest-structure, this can be done in two ways:

By importing and manually adding it to Jest:

```javascript
import jestStructure from 'jest-structure';

expect.extend(jestStructure);
```

Or by allowing jest-structure to add itself to Jest matchers:

```javascript
import 'jest-structure/extend-expect';
```

Both ways can be done in a [setup file](https://jestjs.io/docs/en/configuration#setupfilesafterenv-array) or directly at the top of your test file

## Matchers

### `toBeValidStructure()`

This matcher passes if the structure is *valid*:

```javascript
const User = attributes({
  name: { type: String, required: true },
})(class User {});

const validUser = new User({ name: 'Me' });

expect(validUser).toBeValidStructure(); // passes

const invalidUser = new User();

expect(invalidUser).toBeValidStructure(); // fails
```

### `toBeInvalidStructure()`

This matcher passes if the structure is *invalid*:

```javascript
const User = attributes({
  name: { type: String, required: true },
})(class User {});

const invalidUser = new User();

expect(invalidUser).toBeInvalidStructure(); // passes

const validUser = new User({ name: 'Me' });

expect(validUser).toBeInvalidStructure(); // fails
```

## `toHaveInvalidAttribute(path, messages)`

This matcher allows you to assert that a *single attribute* of the structure is invalid, optionally passing the array of error messages for that attribute:

```javascript
const User = attributes({
  name: { type: String, required: true },
  age: { type: Number, required: true },
})(class User {});

const user = new User({ age: 42 });

// passes, because name is invalid
expect(user).toHaveInvalidAttribute(['name']);

// fails, because age is valid
expect(user).toHaveInvalidAttribute(['age']);

// passes, because name is invalid with this message
expect(user).toHaveInvalidAttribute(['name'], ['"name" is required']);

// fails, because name is invalid but not with this message
expect(user).toHaveInvalidAttribute(['name'], ['"name" is not cool']);

// passes. Notice that you can even use arrayContaining to check for a subset of the errros
expect(user).toHaveInvalidAttribute(['name'], expect.arrayContaining(['"name" is required']));

// passes. And stringContaining can be used as well
expect(user).toHaveInvalidAttribute(['name'], [expect.stringContaining('required')]);
```

## `toHaveInvalidAttributes([ { path, messages } ])`

This matcher allows you to assert that *multiple attributes* of the structure are invalid, optionally passing the array of error messages for each attribute:

```javascript
const User = attributes({
  name: { type: String, required: true },
  age: { type: Number, required: true },
})(class User {});

const user = new User({ age: 42 });

// passes, because name is invalid
expect(user).toHaveInvalidAttributes([{ path: ['name'] }]);

// fails, because age is valid
expect(user).toHaveInvalidAttributes([{ path: ['age'] }]);

// fails, because name is invalid but age is valid
expect(user).toHaveInvalidAttributes([{ path: ['name'] }, { path: ['age'] }]);

// passes, because name is invalid with this message
expect(user).toHaveInvalidAttributes([{ path: ['name'], messages: ['"name" is required'] }]);

// fails, because name is invalid but not with this message
expect(user).toHaveInvalidAttributes([{ path: ['name'], messages: ['"name" is not cool'] }]);

// passes. Notice that you can even use arrayContaining to check for a subset of the errros
expect(user).toHaveInvalidAttributes([
  { path: ['name'], messages: expect.arrayContaining(['"name" is required']) },
]);

// passes. And stringContaining can be used as well
expect(user).toHaveInvalidAttributes([
  { path: ['name'], messages: [expect.stringContaining('required')] },
]);
```


# Battlecry generators

There are configurable [BattleCry](https://github.com/pedsmoreira/battlecry) generators ready to be downloaded and help scaffolding schema:

```bash
npm install -g battlecry
cry download generator talyssonoc/structure
cry g schema user name age:int:required cars:string[] favoriteBook:book friends:user[]:default :updateAge
```

Run `cry --help` to check more info about the generators available;


# Migrating from v1

Migrating an app that uses Structure v1 to use Structure v2 requires some changes in the way validation errors are expected to be returned, default fallback of null values and upgrading Node (if you use a version lower than v10.13.0)

## Validation errors

In v1, validations used to be like this:

```javascript
const Book = attributes({
  name: {
    type: String,
    required: true,
  },
})(class Book {});

const User = attributes({
  initials: {
    type: String,
    minLength: 2,
  },
  favoriteBook: Book,
  books: {
    type: Array,
    itemType: Book,
  },
})(class User {});

const user = new User({
  initials: 'A',
  favoriteBook: new Book(),
  books: [new Book()],
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"initials" length must be at least 2 characters long', path: 'initials' },
  { message: '"name" is required', path: 'favoriteBook.name' },
  { message: '"name" is required', path: 'books.0.name' }
]
*/
```

Notice that the message used to contain only the name of the attribute (so if it's nested it will only show the attribute name of the nested structure) and the path is a string that use a dot `.` to represent that it's a nested attribute.

If your app relies on the content of the message or the path, you'll have to consider that it's now returned like this:

```javascript
const Book = attributes({
  name: {
    type: String,
    required: true,
  },
})(class Book {});

const User = attributes({
  initials: {
    type: String,
    minLength: 2,
  },
  favoriteBook: Book,
  books: {
    type: Array,
    itemType: Book,
  },
})(class User {});

const user = new User({
  initials: 'A',
  favoriteBook: new Book(),
  books: [new Book()],
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"initials" length must be at least 2 characters long', path: ['initials'] },
  { message: '"favoriteBook.name" is required', path: ['favoriteBook', 'name'] },
  { message: '"books[0].name" is required', path: ['books', 0, 'name'] }
]
*/
```

In v2 the message contains the whole path for the attribute (using dot `.` to represent it's a nested attribute) and the path is not an array.

So if your apps relies in the content of the message you'll probably have to do some parsing of this message now. And if it relies in the path to be a string, you can use [`path.join('.')`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join).

## Nullability and defaults

Since v2 now allows having nullable attributes, non-nullable attributes will fallback to the [default](/schema-concept/shorthand-and-complete-attribute-definition#default) the same way it happens with attributes with `undefined` value since v1.

## New public methods

Structure v2 also adds two new instance methods to the structures: `instance.get(attrName)` and `instance.set(attrName, attrValue)`. They are **not** replacing the normal getters and setters, which are still there, they are just alternatives for the case you use a [custom setter and/or getter](/custom-setters-and-getters)

So if any of your structures declare methods with these names you'll have to change it or it's gonna break.

## Upgrade Node

The minimum Node LTS supported by Structure is now v10.13.0 which is the lowest active [LTS](https://nodejs.org/en/about/releases/).


# Support and compatibility

Structure is built on top of modern JavaScript, using new features like [Proxy](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy), [Reflect](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect) and [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol). That being so, there are some things regarding compatibility you should consider when using Structure.

## Node

Node has only implemented all the used features at version 10, so to use Structure for a backend application you'll need Node 10 or later.

## Browser

We have a UMD version for usage in browsers. Right now the tests are ran both in Node (using the original code) and in Electron (using the UMD version) and the whole test suite passes for both cases. Since we use modern JavaScript features inside the lib (like [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)), older browsers may not support it. Polyfilling them may be an option but it's not oficially supported.


# Changelog

## 2.0.1 - 2020-06-15

Fix:

* Fix deep nested dynamic types validation \[[#132](https://github.com/talyssonoc/structure/issues/132)]

## 2.0.0 - 2020-03-31

Refactors:

* The whole part of schemas and attribute definitions was refactored
* Tests are now run by Jest (and Electron for browser tests)
* Prettier was added
* Move to mono-repo

Enhancements

* Implement jest-structure assertions
* It's possible to set custom getters e setters directly in the structure class
* Allows to disable coercion

Breaking changes:

* Joi is updated to v16
  * Attribute path in validation *errors* is an array instead of a string
  * Attribute path in validation *messages* contains the whole path joined by '.'
  * The name used for the dynamic import should aways be the same as the name of its type or else a custom identifier must be used
* Non-nullable attributes with value null will use default value the same way undefined does
* Structure classes now have two methods to generically set and get the value of the attributes, `.get(attributeName)` and `.set(attributeName, attributeValue)`
* Minimum Node version is now 10

Docs:

* Rename the term `type descriptor` to `attribute definition` in the docs and in the code
* Reorganize and add more specific pages to docs

## 2.0.0-alpha.4 - 2020-03-21

* Publish only src folder for jest-structure

## 2.0.0-alpha.3 - 2020-03-20

* Reorganize md files

## 2.0.0-alpha.2 - 2020-03-19

* Invert symlinks

## 2.0.0-alpha.1 - 2020-03-19

* Add symlinks to md files to packages/structure

## 2.0.0-alpha.0 - 2020-03-19

Refactors:

* The whole part of schemas and attribute definitions was refactored
* Tests are now run by Jest (and Electron for browser tests)
* Prettier was added
* Move to mono-repo

Enhancements

* Implement jest-structure assertions
* It's possible to set custom getters e setters directly in the structure class

Breaking changes:

* Joi is updated to v16
  * Attribute path in validation *errors* is an array instead of a string
  * Attribute path in validation *messages* contains the whole path joined by '.'
  * The name used for the dynamic import should aways be the same as the name of its type or else a custom identifier must be used
* Non-nullable attributes with value null will use default value the same way undefined does
* Structure classes now have two methods to generically set and get the value of the attributes, `.get(attributeName)` and `.set(attributeName, attributeValue)`
* Minimum Node version is now 10

## 1.8.0 - 2019-09-16

Enhancements:

* Add `unique` validation to arrays

## 1.7.0 - 2019-09-14

Enhancements:

* Add method to clone structures

## 1.6.0 - 2019-08-27

Enhancements:

* Allow custom error class to static mode

## 1.5.0 - 2019-07-08

Enhancements:

* Add `buildStrict` static method

## 1.4.0 - 2019-03-26

Enhancements:

* Add `nullable` option

## 1.3.2 - 2019-03-22

Fix:

* The actual instance is passed to the dynamic defaults

## 1.3.0 - 2018-03-23

Enhancements:

* When using default function to initialize attributes you can now refer to another attribute values to compose value

## 1.2.0 - 2017-02-01

Features:

* Allow circular reference on type definitions ([@talyssonoc](https://github.com/talyssonoc/structure/pull/30))

Enhancements:

* Make validation faster ([@talyssonoc](https://github.com/talyssonoc/structure/pull/28))

Dependencies update:

* Update joi from 9.2.0 to 10.2.0 ([@talyssonoc](https://github.com/talyssonoc/structure/pull/26))

## 1.1.0 - 2017-01-17

* Added static method `validate()` to structures ([@talyssonoc](https://github.com/talyssonoc/structure/pull/25))


# Contributing

Contributions are always welcome! When contributing to Structure we ask you to follow our code of conduct:

## Code of conduct

In short: *Be nice*. Pay attention to the fact that Structure is free software, don't be rude with the contributors or with people with questions and we'll be more than glad to help you. Destructive criticism and demanding will be ignored.

## Opening issues

When opening an issue be descriptive about the bug or the feature suggestion, don't simply paste the error message on the issue title or description. Also, **provide code to simulate the bug**, we need to know the exact circumstances in which the bug occurs. Again, follow our [code of conduct](/contributing#code-of-conduct).

## Pull requests

When opening a pull request to Structure, follow this steps:

1. Fork Structure;
2. Create a new branch for your changes;
3. Do your changes;
4. Write tests for your changes;
5. Check the coverage;
6. Open the pull request;
7. Write a complete description about the bug or the feature the pull request is about.

Be aware that we keep **100% of code coverage**, any change that makes the code coverage less than 100% covered will be requested to write more tests.


# License

MIT License

Copyright (c) 2017 Structure

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


# Introduction

## A simple schema/attributes library built on top of modern JavaScript

## [![npm](https://img.shields.io/npm/v/structure.svg?style=flat)](https://www.npmjs.com/package/structure) [![Build Status](https://travis-ci.org/talyssonoc/structure.svg?branch=master)](https://travis-ci.org/talyssonoc/structure) [![Coverage Status](https://coveralls.io/repos/github/talyssonoc/structure/badge.svg?branch=master)](https://coveralls.io/github/talyssonoc/structure?branch=master) [![Code Climate](https://codeclimate.com/github/talyssonoc/structure/badges/gpa.svg)](https://codeclimate.com/github/talyssonoc/structure) [![JS.ORG](https://img.shields.io/badge/js.org-structure-ffb400.svg?style=flat)](https://js.org/)

Structure provides a simple interface which allows you to add attributes to your ES6 classes based on a schema, with validations and type coercion.

## Use cases

You can use Structure for a lot of different cases, including:

* Domain entities and value objects
* Model business rules
* Validation and coercion of request data
* Map pure objects and JSON to your application classes
* Add attributes to classes that you can't change the class hierarchy

Structure was inspired by Ruby's [Virtus](https://github.com/solnic/virtus).

What Structure is **not**:

* It's not a database abstraction
* It's not a MVC framework (but it can be used to domain entities)
* It's not an attempt to simulate classic inheritance in JavaScript

## Getting started

`npm install --save structure`

## Usage

For each attribute on your schema, a getter and a setter will be created into the given class. It'll also auto-assign those attributes passed to the constructor.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: String,
  age: {
    type: Number,
    default: 18
  },
  birthday: Date
})(class User {
  greet() {
    return `Hello ${this.name}`;
  }
});

/* The attributes "wraps" the Class, still providing access to its methods: */

const user = new User({
  name: 'John Foo'
});

user.name; // 'John Foo'
user.greet(); // 'Hello John Foo'
```

## Support and compatibility

Structure is built on top of modern JavaScript, using new features like [Proxy](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy), [Reflect](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Reflect) and [Symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol). That being so, there are some things regarding compatibility you should consider when using Structure.

### Node

Node only implemented all the used features on version 6, so for using Structure for a backend application you'll need Node 6 or later.

### Browser

Not all major browsers implemented the used features so you'll need to transpile the code for using it. For browser usage we have the [UMD version](https://github.com/talyssonoc/structure/blob/master/dist/structure.js) bundled with Webpack. We don't bundle Structure with its dependencies so you'll have to provide it with your module bundler. It's recommended to replace joi with [joi-browser](https://www.npmjs.com/package/joi-browser) when using it on the front-end, here's how we run our test suite on the browser regarding [bundling](https://github.com/talyssonoc/structure/blob/master/test/karma.conf.js#L3-L11) and [polyfill of features](https://github.com/talyssonoc/structure/blob/master/test/browserSetup.js#L1-L2).

Be aware that not the whole test suite will pass on browsers, there are some cases that can't be simulated through polyfilling, like extending Array or having a non-structure class extending a structure class. You can setup the project on your computer and run npm run test:browser to see how it'll work.

Right now 95.5% of the tests will pass on Chrome 55, and 95% will pass on Firefox 45. We intend to make it support older versions using polyfills in the next releases.

## BattleCry generators

There are configurable [BattleCry](https://github.com/pedsmoreira/battlecry) generators ready to be downloaded and help scaffolding schema:

```bash
npm install -g battlecry
cry download generator talyssonoc/structure
cry g schema user name age:int:required cars:string[] favoriteBook:book friends:user[]:default :updateAge
```

Run `cry --help` to check more info about the generators available;

## [Contributing](/v1/contributing)

## [LICENSE](/v1/license)


# Schema concept

The schema is an object responsible to map the attributes Structure should handle, it is the parameter of the `attributes` function.

```javascript
attributes({
  name: String,
  age: Number
})(class User { });
```

There are two ways to declare an attribute of the schema, the **shorthand type descriptor** and the **complete type descriptor**.


# Shorthand and complete type descriptor

## Shorthand type descriptor

The shorthand is a pair of `propertyName: Type` key/value like this:

```javascript
const User = attributes({
  name: String,
  brithday: Date
})(class User {
  generateRandomBook() {
    return '...';
  }
});
```

## Complete type descriptor

The complete descriptor allows you to declare additional info for the attribute. **For Array types it's required to use the complete type descriptor because you must specify the `itemType`**.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous'
  },
  cars: {
    type: Array,
    itemType: String,
    default: ['Golf', 'Polo']
  },
  book: {
    type: String,
    default: (instance) => instance.generateRandomBook()
  }
})(class User {
  generateRandomBook() {
    return '...';
  }
});
```

### default

The **default** of an attribute will be used if no value was provided for the specific attribute at construction time.

You can also use a function which receives the instance as a parameter in order to provide the default. The operation must be synchronous and the function will called after all the other attributes are already assigned, thus, you can use the other attributes of your class to compose a default value.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous' // static default value
  },
  greeting: {
    type: String,
    default: (instance) => instance.greeting() // dynamic default value
  }
})(class User {
  greeting() {
    return `Hello ${this.name}`;
  }
});
```

Please note that initializing an attribute with undefined will make it fallback to the default value while instantiating the structure, but it will not fallback when assigning the attribute after the structure is already constructed.

```javascript
const User = attributes({
  name: {
    type: String,
    default: 'Anonymous' // static default value
  }
})(class User { });

const firstUser = new User({ name: undefined });
firstUser.name; // 'Anonymous' =>  fallbacks to default value

const secondUser = new User({ name: 'Some name' });

secondUser.name = undefined;
secondUser.name; // undefined => does not fallback to default value
```

### itemType

The **itemType** of an attribute is used to validate and coerce the type of each item from the attribute, like when the attribute type is `Array` or some class that extends `Array`.

* Please refer to [Validation](/v1/validation) in order to check a bit more on validation properties.

## Type concept

Each attribute needs a **type** definition, that's how Structure validates and coerces the attribute's value. It can be divided into three categories (as in right now):

* Primitives (Number, String, Boolean)
* Classes (Date, Object, regular Classes and Structure classes as well)
* Array/Array-like (Array, extended Array)


# Circular reference

Sometimes we may need to have a type reference itself in its attributes, or have two types that reference eachother in separate files, it can be a complication because it's not possible to do this using the type definitions like we did before. For cases like this we can use a feature called "dynamic types".

When using dynamic types you can pass a string instead of the type itself in the type definition, and pass an object as the *second* parameter of the `attributes` function with an object with a key called `dynamics`. This key will have functions named after the dynamic attribute types, that will be called when the given type is used, like this:

```javascript
/*
 * User.js
*/
const User = attributes({
  name: String,
  friends: {
    type: Array,
    itemType: 'User' // << dynamic type name
  },
  favoriteBook: {
    type: 'Book', // << dynamic type name
    required: true
  },
  books: {
    type: 'BooksCollection', // << dynamic type name
    itemType: String
  }
}, {
  dynamics: { // << dynamic types values
    User: () => User,
    Book: () => require('./Book'),
    BooksCollection: () => require('./BooksCollection')
  }
})(class User { });

/*
 * Book.js
*/
const Book = attributes({
  name: String,
  owner: 'User', // << dynamic type name
  nextBook: 'Book' // << dynamic type name
}, {
  dynamics: { // << dynamic types values
    User: () => require('./User'),
    Book: () => Book
  }
})(class Book { });
```

Notice that the *name* of the type has to be the same name of the key inside the `dynamics` object. Also, it's important that the require be done **inside** the function when the dynamic type also references the current type (in the example above, the type `User` has an attribute of the type `Book`, and the type `Book` has an attribute of the type `User`).


# Nullable attributes

You can change the way an attribute is treated when the value `null` is assigned to it by using the `nullable` option with the value `true`, this would affect the way the attribute is coerced, validated and serialized.

If you do not set the `nullable` option for an attribute it will default to `false` and make your attribute **not nullable**.

```javascript
/*
 * User.js
*/
const User = attributes({
  name: {
    type: String,
    empty: true
  },
  age: Number,
  active: Boolean,
  createdAt: Date
})(class User { });

const user = new User({
  name: null,
  age: null,
  active: null,
  createdAt: null
});

user.attributes; // { name: '', age: 0, active: false, createdAt: 1970-01-01T00:00:00.000Z }
user.validate() // { valid: true }
```

## Nullable optional attributes

When you set an optional attribute to be **nullable** you are choosing not to assign a default value for it when instantiating your structure passing `null` as the value of this attribute, so the actual value will be `null` and will be considered valid.

```javascript
/*
 * User.js
*/
const User = attributes({
  name: {
    type: String,
    nullable: true
  }
})(class User { });

const user = new User({
  name: null
});

user.attributes; // { name: null }
user.validate() // { valid: true }
```

## Nullable required attributes

We consider that when an attribute is **required** there should be some value assigned to it even if it's `undefined`, `null` or any other value. It means that coercion will never assign a **default** value to **required** attributes even if **nullable** option is **false**.

```javascript
/*
 * User.js
*/
const User = attributes({
  name: {
    type: String,
    required: true,
    nullable: false // non-nullable required attribute
  }
})(class User { });

const user = new User({
  name: null
});

user.attributes; // { name: null }
user.validate() // { valid: false }
```

But notice that you can choose to allow **null** values on **required** attributes which will cause the validation to return **true**.

```javascript
/*
 * User.js
*/
const User = attributes({
  name: {
    type: String,
    required: true,
    nullable: true
  }
})(class User { });

const user = new User({
  name: null
});

user.attributes; // { name: null }
user.validate() // { valid: true }
```

**Important:**

* Notice that by not using the `nullable` option the **default** value for **String** is an empty string, which means that you need to accept empty strings to make your schema valid.
* Notice that usually an attribute with the value **undefined** or **null** is not included when you serialize your structure, but when it is **nullable** this attribute is going to be returned in your serialized schema.


# Coercion

Structure does type coercion based on the declared [schema](/v1/schema-concept). It's important to note that it **never** coerces the following scenarios:

* `undefined`;
* `null` when `nullable` option is enabled;
* value is already of the declared type (except for arrays, we'll talk more about this soon).

Let's break the coercion into 3 categories.


# Primitive type coercion

It's said to be primitive type coercion when it tries to coerce values to `String`, `Number` or `Boolean` types.

For those types we basically use the type as a function (without using `new`), with a subtle difference: When coercing `null` to `String`, it'll coerce to empty string instead of the string `'null'`. For example:

```javascript
const User = attributes({
  name: String,
  age: Number,
  isAdmin: Boolean
})(class User { });

const userOne = new User({
  name: 'Foo Bar',
  age: 50,
  isAdmin: true
});

userOne.name; // 'Foo Bar' => no coercion was done
userOne.age; // 50 => no coercion was done
userOne.isAdmin; // true => no coercion was done

const userTwo = new User({
  name: null,
  age: '100',
  isAdmin: undefined
});

userTwo.name; // '' => coerced `null` to empty string
userTwo.age; // 100 => coerced string to number
userTwo.isAdmin; // undefined => it'll never coerce `undefined`
```


# Arrays coercion

It's also possible to coerce values to `Array` or some other class that extends `Array`. On these circumstances Structure will use the `itemType` value of the type descriptor on the schema to coerce the items as well. Note that, when coercing arrays, it'll always create a new instance of the type and then push each item of the passed value to the new instance:

```javascript
class BooksCollection extends Array { }

const Library = attributes({
  books: {
    type: BooksCollection,
    itemType: String
  },
  users: {
    type: Array,
    itemType: String
  }
})(class Library { });

const libraryOne = new Library({
  books: ['Brave New World'],
  users: ['John', 'Jane']
});

libraryOne.books; // BooksCollection ['Brave New World'] => coerced the array to BooksCollection
libraryOne.users; // ['John', 'Jane'] => new instance of Array
```

The passed raw value have to be non-null and have a `length` attribute or implement the `Symbol.iterator` method, otherwise it'll fail to coerce and throw a `TypeError`.


# Generic coercion

If the declared type is not a primitive nor Array (or an array subclass) it'll do generic coercion. When generic coercing a value, Structure will just instantiate the declared type (using `new`) passing the raw value as the parameter (only if the raw value isn't of the declared type already).

```javascript
class Location {
  constructor({ x, y }) {
    this.x = x;
    this.y = y;
  }
}

const User = attributes({
  location: Location
})(class User { });

const userOne = new User({
  location: new Location({ x: 1, y: 2 })
});

userOne.location; // Location { x: 1, y: 2 } => no coercion was done


const userTwo = new User({
  location: { x: 3, y: 4 }
});

userTwo.location; // Location { x: 3, y: 4 } => coerced plain object to Location
```

Coercion to `Date` type enters in this same category, so if you have an attribute of the type `Date`, it'll use `new Date(<raw value>)` to coerce it. For more info about how this coercion works check the cases for `value` and `dateString` parameters on [Date documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date).


# Recursive coercion

Structure also does recursive coercion so, if your declared type is Array or other Structure, the items/attributes of the raw value will be coerced as well:

```javascript
class BooksCollection extends Array { }

const Book = attributes({
  name: String
})(class Book { });

const User = attributes({
  favoriteBook: Book,
  books: {
    type: BooksCollection,
    itemType: Book
  }
})(class User { });

const user = new User({
  favoriteBook: { name: 'The Silmarillion' },
  books: [
    { name: '1984' }
  ]
});

user.favoriteBook; // Book { name: 'The Silmarillion' } => coerced plain object to Book
user.books; // BooksCollection [ Book { name: '1984' } ] => coerced array to BooksCollection and plain object to Book
```


# Observations

**Important: Structure only does coercion during object creation, so mutating an array (using push, for example) won't coerce the new item:**

```javascript
const Library = attributes({
  books: {
    type: Array,
    itemType: String
  }
})(class Library { });

const library = new Library({
  books: [1984]
});

library.books; // ['1984'] => coerced number to string

library.books.push(42);

library.books; // ['1984', 42] => new item was not coerced
```


# Validation

A `validate()` method will be added to the prototype of structures, this method will validate the structure based on its schema. The method will return an object with the property `valid` (with the value `true` if it's valid, and `false` if invalid). If `valid` is `false` the returned object will also have a property `errors`, with an array of validation errors.

Validations require you to use the complete type descriptor:

```javascript
const User = attributes({
  name: {
    type: String,
    minLength: 10
  },
  age: {
    type: Number,
    required: true
  }
})(class User { });

const user = new User({
  name: 'John'
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"name" length must be at least 10 characters long', path: 'name' },
  { message: '"age" is required', path: 'age' }
]
*/

const validUser = new User({
  name: 'This is my name',
  age: 25
});

const validation = validUser.validate();

validation.valid; // true
validation.errors; // undefined, because `valid` is true
```

Structure has a set of built-in validations built on top of the awesome [joi](https://www.npmjs.com/package/joi) package:

**Observations**

Validations marked with **\*** accept a value, an [attribute reference](/v1/validation/attribute-reference), or an array of values and attribute references mixed.

Validations marked with **\*\*** accept a value or an [attribute reference](/v1/validation/attribute-reference).


# String validations

* `required`: can't be undefined (default: `false`)
* `empty`: accepts empty string (default: `false`)
* `equal`: **\*** equal to passed value
* `minLength`: can't be shorter than passed value
* `maxLength`: can't be longer than passed value
* `exactLength`: length must be exactly the passed value&#x20;
* `regex`: matches the passed regex
* `alphanumeric`: composed only by alphabetical and numeric characters
* `lowerCase`: all characters must be lower cased
* `upperCase`: all characters must be upper cased
* `email`: is a valid email (default: `false`)
* `nullable`: accepts null (default: `false`)
* `guid`: is a valid guid. You can pass a boolean or the [options object accepted by Joi](https://github.com/hapijs/joi/blob/v10.2.0/API.md#stringguid---aliases-uuid) (default: `false`)

```javascript
const User = attributes({
  id: {
    type: String,
    guid: true
  },
  token: {
    type: String,
    guid: {
      version: ['uuidv4']
    }
  },
  initials: {
    type: String,
    upperCase: true,
    maxLength: 4
  },
  gender: {
    type: String,
    nullable: true
  },
  password: String,
  passwordConfirmation: {
    type: String,
    equal: { attr: 'password' }
  },
  greet: {
    type: String,
    required: true,
    equal: ['Mr', 'Ms', 'Mrs', 'Miss', { attr: 'greetDesc' }]
  },
  greetDesc: String
})(class User {
  getFullGreet() {
    return `${this.greet} ${this.initials}`;
  }
});
```


# Number validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `integer`: must be an integer (default: `false`)
* `precision`: maximum number of decimal places
* `positive`: must be positive (default: `false`)
* `negative`: must be negative (default: `false`)
* `multiple`: must be a multiple of the passed value
* `min`: **\*\*** minimum valid value (works like the `>=` operator)
* `greater`: **\*\*** must be greater than passed value (works like the `>` operator)
* `max`: **\*\*** maximum valid value (works like the `<=` operator)
* `less`: **\*\*** must be smaller than passed value (works like the `<` operator)
* `nullable`: accepts null (default: `false`)

```javascript
const Pool = attributes({
  depth: {
    type: Number,
    positive: true
  },
  width: {
    type: Number,
    min: { attr: 'depth' }
  },
  length: {
    type: Number,
    greater: { attr: 'width' }
  },
  capacity: {
    type: Number,
    nullable: true
  }
})(class Pool {
  getVolume() {
    return this.depth * this.width * this.length;
  }
});
```


# Boolean validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `nullable`: accepts null (default: `false`)

```javascript
const User = attributes({
  isAdmin: {
    type: Boolean,
    required: true
  },
  hasAcceptedTerms: {
    type: Boolean,
    nullable: true
  }
})(class User { });
```


# Date validations

* `required`: can't be undefined (default: `false`)
* `equal`: **\*** equal to passed value
* `min`: **\*\*** must be after passed date
* `max` **\*\*** must be before passed date
* `nullable`: accepts null (default: `false`)

```javascript
const Product = attributes({
  fabricationDate: {
    type: Date,
    default: () => Date.now()
  },
  expirationDate: {
    type: Date,
    min: { attr: 'fabricationDate' }
  },
  createdAt: {
    type: Date,
    nullable: true
  }
})(class Product { });
```


# Array validations

* `required`: can't be undefined (default: `false`)
* `sparse`: can have undefined items (default: `true`)
* `unique`: can't have duplicate items (default: `false`)
* `minLength`: minimum quantity of items
* `maxLength`: maximum quantity of items
* `exactLength`: exact quantity of items

```javascript
const Group = attributes({
  members: {
    type: Array,
    itemType: String,
    minLength: 2,
    maxLength: 5,
    sparse: false,
    unique: true
  },
  leaders: {
    type: Array,
    itemType: String,
    minLength: 1,
    maxLength: { attr: 'members' }
  }
})
```


# Attribute reference

You can reference attributes for some validations so the value of the referenced attribute will be used for the comparison:

```javascript
const User = attributes({
  name: String,
  password: String,
  passwordConfirmation: {
    type: String,
    equal: { attr: 'password' }
  }
})(class User { });

const user = new User({
  name: 'Gandalf',
  password: 'safestpasswordever',
  passwordConfirmation: 'notthatsafetho'
});

const { valid, errors } = user.validate();

valid; // false
errors; /* [
  {
    message: '"passwordConfirmation" must be one of [ref:password]',
    path: 'passwordConfirmation'
  }
]
*/
```


# Nested validations

Structure will validate nested values, including array items validations and nested structures.

```javascript
const Book = attributes({
  name: {
    type: String,
    required: true
  }
})(class Book { });

const User = attributes({
  initials: {
    type: String,
    minLength: 2
  },
  favoriteBook: Book,
  books: {
    type: Array,
    itemType: Book
  }
})(class User { });

const user = new User({
  initials: 'A',
  favoriteBook: new Book(),
  books: [new Book()]
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"initials" length must be at least 2 characters long', path: 'initials' },
  { message: '"name" is required', path: 'favoriteBook.name' },
  { message: '"name" is required', path: 'books.0.name' }
]
*/
```


# Validate raw data

In addition to the *instance* `validate()` method, Structure also adds a *static* `validate()` to your structure classes that receives a *raw object* or a *structure instance* as parameter and has the same return type of the [normal validation](/v1/validation):

```javascript
const User = attributes({
  name: {
    type: String,
    minLength: 10
  },
  age: {
    type: Number,
    required: true
  }
})(class User { });

// Using a raw object
const rawData = {
  name: 'John'
};

const { valid, errors } = User.validate(rawData);

valid; // false
errors; /*
[
  { message: '"name" length must be at least 10 characters long', path: 'name' },
  { message: '"age" is required', path: 'age' }
]
*/

// Using a structure instance
const user = new User({
  name: 'Some long name'
});

const validation = User.validate(user);

validation.valid; // false
validation.errors; /*
[
  { message: '"age" is required', path: 'age' }
]
*/
```


# Strict mode

To instantiate a structure that automatically throws an error if that is invalid, you can use the buildStrict function.

```javascript
const { attributes } = require('structure');
const User = attributes({
    name: {
      type: String,
      required: true
    },
    age: Number
})(class User {});

var user = User.buildStrict({
  age: 'Twenty'
});

// Error: Invalid Attributes
// details: [
//   { message: '"name" is required', path: 'name' },
//   { message: '"age" must be a number', path: 'age' }
// ]
```

## Custom error

Normally `buildStrict` will throw a default `Error` when attributes are invalid but you can customize the error class that will be used passing a `strictValidationErrorClass` to the *second* parameter of the `attributes` function.

The value of `strictValidationErrorClass` should be a class that accepts an array of erros in the constructor.

```javascript
const { attributes } = require('structure');

class InvalidBookError extends Error {
  constructor(errors) {
    super('Wait, this book is not right');
    this.code = 'INVALID_BOOK';
    this.errors = errors;
  }
}

const Book = attributes({
    name: {
      type: String,
      required: true
    },
    year: Number
}, {
  strictValidationErrorClass: InvalidBookError
})(class Book {});

var book = Book.buildStrict({
  year: 'Twenty'
});

// InvalidBookError: Wait, this book is not right
// code: 'INVALID_BOOK'
// details: [
//   { message: '"name" is required', path: 'name' },
//   { message: '"year" must be a number', path: 'year' }
// ]
```


# Cloning an instance

Structure adds a method `#clone` in order to be able to create a **shallow** copy of an instance. This methods accepts an optional overwrite object that permits you to overwrite some attributes of the copy.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: String,
})(class User {});

const user = new User({
  name: 'Me',
});

const cloneUserWithNoOverwrite = user.clone(); // User { name: 'Me }

const cloneWithOverwrite = user.clone({ name: 'Myself' }); // User { name: 'Myself' }
```

If the structure has a nested structure inside of it, the `#clone` method **will not** clone it but just point the new instance to the old value of the nested attribute.

```javascript
const { attributes } = require('structure');

const Book = attributes({
  name: String,
})(class Book {});

const User = attributes({
  name: String,
  favoriteBook: Book,
})(class User {});

const user = new User({
  name: 'Me',
  favoriteBook: new Book({ name: 'The Silmarillion' }),
});

const cloneUserWithNoOverwrite = user.clone();
cloneUserWithNoOverwrite.favoriteBook === user.favoriteBook; // true, it was not cloned

const cloneWithOverwrite = user.clone({
  favoriteBook: { name: 'The Lord of the Rings' },
});
cloneWithOverwrite.favoriteBook === user.favoriteBook; // false, it was **replaced** with the new value
cloneWithOverwrite.favoriteBook; // Book { name: 'The Lord of the Rings' }
```

## Strict mode

When cloning an instance, you can clone it in [strict mode](/v1/strict-mode) as well, so if the resulting clone is invalid it throws an error. To do that, pass a second argument to the `#clone` method with the option `strict` as `true`.

```javascript
const { attributes } = require('structure');

const User = attributes({
  name: {
    type: String,
    required: true,
  },
  age: Number,
})(class User {});

const user = new User({
  name: 'Me',
});

const clonedUser = user.clone(
  { name: null },
  { strict: true } // strict mode option
);

// Error: Invalid Attributes
// details: [
//   { message: '"name" is required', path: 'name' }
// ]
```


# Serialization

It's possible to obtain a serialized object of a Structure using the method `toJSON()`. This method is also compliant with the [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) specification, so you can use it to serialize your object too.

**Important:**

* Be aware that `toJSON()` will return an object, not the JSON in form of a string like `JSON.stringify()` does
* Refer to the [Date#toJSON](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) specification to see how dates will be serialized by `JSON.stringify`
* Refer to [Dealing with nullable attributes](/v1/schema-concept/nullable-attributes) to check how `nullables` are going to be returned on **Serialization**

```javascript
const Book = attributes({
  name: String
})(class Book { });

const User = attributes({
  name: String,
  birth: Date,
  books: {
    type: Array,
    itemType: Book
  }
})(class User { });

const user = new User({
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    new Book({ name: 'The name of the wind' }),
    new Book({ name: 'Stonehenge' })
  ]
});

user.toJSON(); /* {
  name: 'John Something',
  birth: new Date('10/10/1990'),
  books: [
    { name: 'The name of the wind' },
    { name: 'Stonehenge' }
  ]
}
*/

JSON.stringify(user)); // {"name":"John Something","birth":"1990-10-10T03:00:00.000Z","books":[{"name":"The name of the wind"},{"name":"Stonehenge"}]}
```


# Contributing

Contributions are always welcome! When contributing to Structure we ask you to follow our code of conduct:

## Code of conduct

In short: *Be nice*. Pay attention to the fact that Structure is free software, don't be rude with the contributors or with people with doubts and we'll be more than glad on helping you. Destructive criticism and demanding will be ignored.

## Opening issues

When opening an issue be descriptive about the bug or the feature suggestion, don't simply paste the error message on the issue title or description. Also, **provide code to simulate the bug**, we need to know the exact circumstances in which the bug occurs. Again, follow our [code of conduct](/v1/contributing#code-of-conduct).

## Pull requests

When opening a pull request to Structure, follow this steps:

1. Fork Structure;
2. Create a new branch for your changes;
3. Do your changes;
4. Write tests for your changes;
5. Check the coverage;
6. Open the pull request;
7. Write a complete description about the bug or the feature the pull request is about.

Be aware that we keep **100% of code coverage**, any change that makes the code coverage less than 100% covered will be requested to write more tests.


# License

MIT License

Copyright (c) 2017 Structure

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


