Skip to content

Feature request : default values and required for object fields #3587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
AmbroiseCollon opened this issue Mar 1, 2017 · 7 comments · Fixed by #5835
Closed

Feature request : default values and required for object fields #3587

AmbroiseCollon opened this issue Mar 1, 2017 · 7 comments · Fixed by #5835

Comments

@AmbroiseCollon
Copy link

Inspired from meteor.js technology, it could be a really valuable addition to add two properties to object fields :

  • Required boolean : if a required field is left empty, save operation crashes
  • Default values : if a field is not set, a default values can be selected

A field with a default value should be required. It would save a lot of dumb code in before and after save method.

Process could be like :

  1. Object is created
  2. Save method is called on object
  3. All fields are checked. For each field :
    a. if the object has already a value for the field => OK
    b. if the object has no value for the field :
    i. if field is not required => OK
    ii. if field is required :
    - if field has a default value => fill field with default value
    - if field has no default value => Error : field cannot be undefined

Maybe the easiest way to do this is to create meta collection aside from actual collection that owns all this required / default value data. But this is where my understanding of Parse Server behind the scenes stops.

What do you think ?

@acinader
Copy link
Contributor

one way to achieve this is through a beforeSave hook in cloud code. In the beforeSave hook you can validate a submission and set any default values.

I could see an argument for adding the ability to set validation for a class in the dashboard obviating the need for doing it programatically.

@AmbroiseCollon
Copy link
Author

AmbroiseCollon commented Mar 28, 2017

The beforeSave hook is what I'm using now. But it much more elegant to just be able to set it directly in the dashboard. And it saves many lines of repeated code throughout the classes.

@yomybaby
Copy link
Contributor

I agree with @AmbroiseCollon . If Schema has required field option, it saves many boring codes. :)

@flovilmart
Copy link
Contributor

@AmbroiseCollon , @yomybaby any one of you wanting to get started on that feature?

@c0sm1cdus7
Copy link

Any news on this? Just wanted to know before starting to code the beforeSave from my app.

@milesrichardson
Copy link

milesrichardson commented Dec 15, 2017

I have a library called parseConstraints I use for this in beforeSave. The code is old and a huge mess / needs to be refactored, so I would rather not share it. But here is what the general API looks like when used in a beforeSave trigger:

static beforeSave(ParseConstraints, req, res) {
        var parseConstraints = new ParseConstraints(req, res, 'Fund');

        return parseConstraints.existsKeys([
            'fundName'
        ])
        .then(() => parseConstraints.defaults({
                'fundManagers': [],
                'fundClosingDates': []
        }))
        .then(() => {
            /// .....
        })
       .then(() => {
            return res.success();
        }).catch((err) => {
            res.error(err);
        });
    }

Each parseConstraints function will reject a promise if there is an error. Other functions I've got include keysHaveValidValues, objectsInArrayHaveKeys, capitalizeKeys, lowercaseKeys, uniqueKeys (this is better implemented as an index so as not to require extra query), uniqueMultipleKeys

This is what the basic code for existsKeys and defaults looks like (very old code from Parse.com era):

/* parseConstraints.js */

var DB = function(req, res, className) {
	this.req = req;
	this.res = res;
	this.className = className;
};


// The included keys must exist for the object to be saved
DB.prototype.existsKeys = function(keys) {
	// eslint-disable-next-line
	var p = new Parse.Promise();
	var object = this.req.object;

	keys = _toArray(keys);

	for (var i = 0; i < keys.length; i++) {
		var key = keys[i];
		var value = object.get(key);

		// The empty string does not count as 'existing'
		if (value === undefined || value === null || (typeof value === 'string' && value.length === 0)) {
			this.res.error('existsKeys Error: A `' + this.className + '` requires a value for key `' + key + '`');
			p.reject(key);
			return p;
		}
	}

	p.resolve(object);
	return p;
}

// Pass in an object with { key: value } for each field and its default value
DB.prototype.defaults = function(defaults) {
	// eslint-disable-next-line
	var p = new Parse.Promise();
	var object = this.req.object;
	var keys = Object.keys(defaults);

	for (var i = 0; i < keys.length; i++) {
		var key = keys[i];
		var value = object.get(key);
		if (value === undefined || value === null) {
			object.set(key, defaults[key]);
		}
	}

	p.resolve(object);
	return p;
};

module.exports = DB;

I might be interested in taking on this feature. My solution would be to define required fields in the schema, preferably complying with the official jsonschema docs. Then perform validation just before the beforeSave trigger, thus emulating what I do with the library. Open to any thoughts on this

@mtrezza mtrezza added the type:feature New feature or improvement of existing feature label Dec 6, 2021
@parse-github-assistant
Copy link

The label type:feature cannot be used in combination with type:improvement.

@parse-github-assistant parse-github-assistant bot removed the type:feature New feature or improvement of existing feature label Dec 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants