Subscribe to our list to receive the latest updates on Node on Fire

Class: PropertyTypes

PropertyTypes

new PropertyTypes()

Members

CurrentAccount

Sets the property to the current account (or authenticator) automatically.

This is a synonym of PropertyTypes#Automatic.

CurrentUser

Sets the property to the current user (or authenticator) automatically.

This is a synonym of PropertyTypes#Automatic.

Methods

Aggregate(aggregateFunctionName, propertyName)

Creates an aggregate property.

For example, the following model creates a minimum aggregate property type.

function Tester() {
    this.name = [this.String];
    this.position = [this.Integer];
    this.minPosition = [this.Aggregate('MIN', 'position')];
}
app.model(Tester);

When retrieving a model instance, the aggregate property is never selected automatically. To select the aggregate property specify the property name in the select option in Model#find.

For example, the below piece fetches the minPosition property:

function TestController(TesterModel) {
    TesterModel.find({}, {groupBy:'name', select: ['name', 'minPosition']});
}

This will return models instances grouped by name including a minPosition property.

Parameters:
Name Type Description
aggregateFunctionName String

The name of the SQL aggregate function, for example, MIN.

propertyName String

The target property name.

Authenticate()

Sets a property to be the authenticating property and sets the model as the authenticator. Currently, there can only be one authenticator.

The authenticator is used for authentication and is e.g. the User or Account model.

To create an authenticator, see the below example:

function User() {
    this.email = [this.String, this.Authenticate];
}
app.model(User);

This creates an authenticator with email as the authenticating property. A password property is automatically created, and an accessToken property is also created which is used for session authentication. The authenticate property is automatically set to be unique.

Several methods are created on an authenticator automatically: Model#authorize, Model#getMe, Model#signOut, Model#resetPassword, Model#forgotPassword.

To sign in an authenticator, see Model#authorize.

AutoFetch()

Set this on an association to automatically fetch all instances when a model instance is retrieved.

If an association is auto-fetched, it's directly available as property on the model instance.

Automatic()

Sets the property to the current authenticator automatically. See PropertyTypes#Authenticate.

BelongsTo(modelNameOrModel, linkedPropertyName)

This property type is part of the association methods. Use this model in a one-to-one or one-to-many association.

The below example shows how to configure a one-to-one association:

function User() {
    this.name = [this.String];
    this.address = [this.HasOne(this.models.UserAddress)]
}
app.model(User);

function UserAddress() {
    this.user = [this.BelongsTo(this.models.User)];
    this.line1 = [this.String];
    this.line2 = [this.String];
}
app.model(UserAddress);
Parameters:
Name Type Description
modelNameOrModel Model | String

The associated model.

linkedPropertyName String

If multiple associations on the target model to this model exists,

Boolean()

Sets the property's data type to BOOLEAN.

Count(propertyName)

Creates a counting property which counts the number of instances in an association.

function Project() {
    this.tasks = [this.HasMany(this.models.Task), this.AutoFetch];
    this.numberOfTasks = [this.Count('tasks')];
}
app.model(Project);
Parameters:
Name Type Description
propertyName String

The name of the property belonging to a one-to-many association.

Date()

Sets the property's data type to DATE.

This only stores the date. Use PropertyTypes#DateTime if you want to include time as well.

DateTime()

Sets the property's data type to TIMESTAMP WITHOUT TIME ZONE.

Decimal(precision, scale)

Sets the property's data type to DECIMAL, see http://www.postgresql.org/docs/current/static/datatype-numeric.html.

Parameters:
Name Type Description
precision

The precision of the number, must be positive.

scale

The scale of the number. 0 or positive.

Default(defaultValue, changePropertyName)

Sets the default value of the property.

You can either provide a string which will be evaluated in the SQL statement, or provide a function, which will be invoked when a new model instance is created.

The below example sets the createdAt's default value to the current time stamp (via SQL statement).

function Article() {
    this.createdAt = [this.DateTime, this.Default('CURRENT_TIMESTAMP')];
}

The below example also sets the createdAt's default value to the current time stamp (via a function).

function Article() {
    this.createdAt = [this.DateTime, this.Default(function() {
        return new Date();
    })];
}

Please note that you can even return a promise in the case of a function. The default value will become the value the promise resolves to.

Parameters:
Name Type Description
defaultValue String | function

The default value, either an SQL string or a function returning a value.

changePropertyName String

Re-set the default value when this property name gets updated.

function()

Defines the property as SERIAL PRIMARY KEY.

Please note that by default a id property is created on every model. The default data type is PropertyTypes#UUID.

Hash(method)

Hashes a property's value before it's inserted in the database or it's searched for in a where map, see Model#find.

This is especially useful if you, for example, want to hash a user's password before it's inserted into the database. For example:

var crypto = require('crypto');

function User() {
    this.email = [this.String];
    this.password = [this.String, this.Required, this.Hash(function(password) {
        var hash = crypto.createHash('sha512');
        hash.update(password);
        return hash.digest('hex');
    })];
}
app.model(User);

This also hashes any values in the where map, for example, if you would query for the user:

this.models.User.findOne({
    email: 'martijn@nodeonfire.org',
    password: 'test'
});

This automatically hashes "test" as well.

Please note, if you want to implement authentication, you are advised to use PropertyTypes#Authenticate instead.

Parameters:
Name Type Description
method function

A function taking 1 argument returning it's hash.

Integer()

Sets the property's data type to INTEGER. This is a synonym of PropertyTypes#Number.

Interval()

Sets the property's data type to INTERVAL.

See http://www.postgresql.org/docs/9.1/static/datatype-datetime.html.

Number()

Sets the property's data type to INTEGER.

PrimaryKey()

Defines the property as primary key on the model.

Private()

Creates a private property. A private property is guaranteed to never get send to the front-end directly (unless otherwise exposed). This is useful for sensitive for things like passwords.

function Project() {
    this.name = [this.String];
    this.secret = [this.String, this.Private];
}

Required()

Sets the property as NOT NULL.

Select(method)

Creates a virtual property which allows you to transform the where clause.

For example, you can create a popular select property and when querying popular articles, only return the articles with more than ten comments.

function Article() {
    this.title = [this.String];
    this.numberOfComments = [this.Integer];
    this.popular = [this.Select(function(popular) {
        if(popular) {
            return {
                numberOfComments: {
                    $gt: 10
                };
            };
        }
    });
}
app.model(Article);

//

models.Article.find({popular: true})
    .then(function(popularArticles) {
        // Do something with the popular articles.
    });
Parameters:
Name Type Description
method function

The select method.

Serial()

SQL(sqlish)

Creates a virtual SQL-ish property.

This allows you to create a static value, or calculated value based on other properties, without actually storing it.

sqlish should be an SQLish string, see Table#parseSQLishStatement for more information on SQLish.

For example:

function Book() {
    this.title = [this.String];
    this.titleLength = [this.SQL('LENGTH($title) * 2')];
}

This creates a book model with a title property and a titleLength property which returns the length of the title times two. This creates a query similar to SELECT title, (LENGTH(title) * 2) as title_length FROM books when querying for books.

A more advanced example:

function Article() {
    this.title             = [this.String, this.Required];
 this.url             = [this.String, this.Required, this.CanUpdate(false), this.Unique];
 this.createdAt         = [this.DateTime, this.Default('CURRENT_TIMESTAMP')];
 this.author         = [this.BelongsTo(this.models.User, 'articles'), this.Automatic, this.Required, this.AutoFetch];
 this.voters         = [this.HasMany(this.models.User, 'votes'), this.AutoFetch];
 this.position         = [this.SQL('($count("voters") - 1) / ((EXTRACT(EPOCH FROM current_timestamp - $createdAt) / 3600) + 2)^1.8')];
}
app.model(Article);
Parameters:
Name Type Description
sqlish String

SQLish statement.

Text()

Sets the property's data type to TEXT.

Text()

Sets the property's data type to TEXT. See PropertyTypes#String which is preferred as it's a less database-specific term.

Time()

Sets the property's data type to TIME WITH TIME ZONE.

Timestamp()

Sets the property's data type to TIMESTAMP WITHOUT TIME ZONE.

Transform(method)

Creates a transform property. A transform property is one or more virtual properties and combined into one property.

function Shoe() {
    this.three = [this.Transform(one, two) {
        return (one * two);
    }];
}
app.model(Shoe);

//

models.Shoe.create({
        one: 3,
        two: 6
 })
    .then(function(shoe) {
        // shoe.three is 18
 });

The transform method is not invoked if any of the transform parameters is undefined. For example, the below example doesn't set three.

models.Shoe.create({
    one: 3
})
.then(function(shoe) {
    // shoe.three is not set via the transform method (thus it's the default value)
})
Parameters:
Name Type Description
method function

The transform method. The property's created are based on this method's arguments.

Unique()

Defines the property as UNIQUE.

Unsigned()

Sets the property to UNSIGNED. This can be used in combination with e.g. PropertyTypes#Number.

Virtual(value)

Sets a property as virtual. Virtual properties are not stored in the database.

Parameters:
Name Type Description
value Boolean

True if virtual, false if not. Defaults to true.

Do you have any questions or comments on this page? Start a discussion below.

comments powered by Disqus
Subscribe to our list to receive the latest updates on Node on Fire