Filter

Socketize allows you to hook into every request. You can write JavaScript to validate any request and manipulate response. It's pure JavaScript, you can use any native JavaScript feature.

Let's imagine, in your app you save every user's name under a key like this:

socketize.set('name', document.getElementById('name-input').value);

Now if someone writes a blank name or a huge name, you can't accept it. You can write this code in your Filter:

if (request.params.key == name && request.params.value == '') {
    request.response = { 'message' : 'Name cannot be blank!', 'code': 400 };
}

This will prevent user from saving a blank name. Surely, such validations can be done in the client side but client side code can be changed. Also Filter has many other use cases.

Request Object

With every request you get a request object. It has some properties, of which some are readonly, means you cannot override it and some of these can be overridden. Below we will get into every property.

request.command

It gives you the name of the command the request wants to execute. For example when socketize.set() is called request.command will return set, for socketize.getListItems() it'll return get_list_items (snake cased). You can override the value to route to a different command.

request.scope

The scope where request is being executed. Values will be user or public or global. You can override the scope.

request.params

The parameters passed to the request. This will have it's own properties like, request.params.key and request.params.value. When a call is made like this socketize.set('country', 'United States'), we call country a key and United States a value. So in filter request.params.key will be counry and request.params.value will be United States.

You can override both key and value. For example append datetime with value:

if (request.command == 'set' && request.params.key == 'country') {
    request.params.value = request.params.value + ' at ' + new Date();
}

request.user

A user object which has details about the currently logged in user. Returns null if not logged in. Available properties are, id, username, email and created_at. Everything is readonly.

request.remote_address

The IP address from which the client is connected and it's readonly.

request.response

It's a write only property. When you set this property the we send this back to client without touching the database. You've to set a JSON object.

request.response = {
    message: 'You are not allowed to perform this action',
    code: 403
};

It will throw an exception in client end which can be caught. The message shown will be the message you provided. The property code here is like HTTP status code, anything other than 200 is considered as an error.