sails.js model validation in bootstrap function - validation

I have a model in sails.js and before creating a new record, I want to validate the data that I wanna insert in model.
this is my model for example :
module.exports = {
attributes: {
levelNumber : {
type : 'string',
defaultTo : '',
required : true,
unique : true
}
}
}
and this is my code that I put in bootstrap.js to run :
MODELNAME.validate({
levelNumber: 10
}, function(err){
if (err && err.invalidAttributes) {
console.log(err.invalidAttributes);
} else {
// model is valid
console.log('validate');
}
});
it always return "validate" and never return error in validation!!!!
my questions is :
1 - how we can validate and input json for a model before creating it ?
thx

Is there a reason to put application logic to bootstrap.js? The fact is sails executed it before the app is lifted, so it is not strange that something is not working correctly.

You can simply add beforeCreate function to your Model definition under api/models
your model will look like this
module.exports = {
attributes: {
.....
},
beforeCreate: function(values, next) {
// Validate the values HERE!!
}
};

Related

Watch Value In Vue.js 3, Equivalent In Pinia?

I have a checkbox list of domain tlds, such as com, net, io, etc. I also have a search text input, where I can drill down the list of 500 or so domains to a smaller amount. For example, if I start to type co in to my search text input, I will get back results that match co, such as co, com, com.au, etc. I am using Laravel and Vue,js 3 to achieve this with a watcher. It works beautifully. How can an achieve the same within a Pinia store?
Here is my code currently:
watch: {
'filters.searchedTlds': function(after, before) {
this.fetchsearchedTlds();
}
},
This is inside my vue component.
Next is the code to fetch searched tlds:
fetchsearchedTlds() {
self = this;
axios.get('/fetch-checked-tlds', { params: { searchedTlds: self.filters.searchedTlds } })
.then(function (response) {
self.filters.tlds = response.data.tlds;
console.log(response.data.tlds);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
},
And finally, the code inside my Laravel controller:
public function fetchCheckedTlds(Request $request)
{
$data['tlds'] = Tld::where('tld', 'LIKE','%'.$request->input('searchedTlds').'%')->pluck('tld');
return response()->json($data);
}
I am converting my code to use a Pinia store and I am stuck on how to convert my vue component watcher to Pinia?
Many thanks in advance.
To watch a pinia status, you may watch a computed attribute based on pinia or use watch getter
Your pinia may look like the one below.
~/store/filters.js
export const useFilters = defineStore('filters', {
state: () => {
return {
_filters: {},
};
},
getters: {
filters: state => state._filters,
},
...
}
In where you want to watch
<script setup>
import { computed, watch } from 'vue';
import { useFilters } from '~/store/filters.js';
const filters = useFilters();
// watch a computed attributes instead
const searchedTlds = computed(() => {
return filters.filters?.searchedTlds || '';
});
watch(
searchedTlds,
(newValue, oldValue) {
fetchsearchedTlds();
}
);
// or use watch getter
watch(
() => {
return filters.filters?.searchedTlds || '';
},
(newValue, oldValue) {
fetchsearchedTlds();
}
);
</script>
The first parameter of watch() can be a single ref or a getter function, or an array of getter functions, for more details, please view the Watch Source Types.

How can I access Vue JS props in a method in a component?

I may be wrong in my understanding of props but I can't seem to be able to pass a prop to a component and then use the value in a method?
So far I am able to get data from a fixed API and output everything from the vue component, now I would like the api source to be dependent on the variable passed to the component.
My blade template:
<projectstatuses :userslug="this-user" :projectslug="this-project"></projectstatuses>
Then in my Vue Component:
export default {
props: {
userslug: {
type: String,
default: "other-user",
},
projectslug: {
type: String,
default: "other-project",
}
},
data() {
return {
statuses : [],
}
},
created(){
this.getStatuses();
},
methods : {
getStatuses(){
console.log(this.userslug);
console.log(this.projectslug);
axios.get('/api/' + this.userslug + '/' + this.projectslug)
.then((response) => {
let statuses = response.data;
this.statuses = statuses.statuses;
console.log(response.data.statuses);
})
.catch(
(response) => {
console.log('error');
console.log(response.data);
}
);
}
}
}
In the console I get the default values, if I remove the default values I get undefined. I have tried removing the api method and simply console logging the values but I still get undefined. Is what I'm trying to do possible or have I completely misunderstood how props work?
You are trying to bind this-user and this-project as a properties not as values ,
So you will need to define them in the data object in the parent,
but if you want to pass this-user and this-project just as value remove the : try that:
<projectstatuses userslug="this-user" projectslug="this-project"></projectstatuses>
Dynamic-Props
Don't add : in your template:
<projectstatuses userslug="this-user" projectslug="this-project"></projectstatuses>
Vue will expect there's data bound to this-user.

How to prevent validate function call while calling model.save in backbone JS

I have a backbone view where I call model.save to create/updated date submitted in the form. Before calling the save I explicitly call model.isValid(true) to validate the form fields then I process the form data to make it ready for API expected format (by adding or modifying additional fields) and then make call to mode.save function which is again triggering validate function where the validations are getting failed due to the modified data. As I have already called the isValid function explicitly, I want to prevent the call again during save. How can I do it in backbone. Here is sample code.
var data = Backbone.Syphon.serialize($(e.currentTarget).closest('form.my_form')[0]));
this.model.set(data);
if(this.model.isValid(true)) {
data['metas'] = this.context.metaData;
data['metas'][0]['locale'] = this.parentObj.model.get('locale');
data['metas'][0]['name'] = data['name'];
delete data['name'];
}
var tempDynAttrs = [];
if(data['dynamicAttributes']){
$.each(data['dynamicAttributes'], function(index,obj) {
if(obj['attributeValue'] !== null && obj['attributeValue'] !== undefined ) {
tempDynAttrs.push({
attributeName: obj['attributeName'],
attributeValue: [obj['attributeValue']],
locale: data['defaultLocale'],
status: 'active'
});
}
});
}
data['dynamicAttributes'] = tempDynAttrs;
this.model.save(data, {
url: this.model.url(),
patch: true,
success : function(model, response) {
$('#headerMessage').html('Data is updated successfully');
},
error : function(model, response) {
$('#headerMessage').html('Error updating data');
}
});
} else {
$('#formPanel').animate({
scrollTop: $('.has-error').first().offset().top-50
}, 100);
return false;
}
Try passing {validate:false} in the save options, like
book.save({author: "Teddy"}, {validate:false});
According to change log of version 0.9.10:
Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed.
So passing {validate:false} should do the trick.

Sails.js and Waterline: dynamic validation by DB request

I use Sails 11.1 and Waterline 2.11.2 with a MongoDB database.
I would like to validate data inserted in my "Article" model using a in validator for 1 attribute.
Before, I was doing the job with lifecycle callbacks (beforeCreate and beforeUpdate especially), but it makes double code.
Here you have the model, truncated with just the attribute in question :
module.exports =
{
schema: true,
autoCreatedAt: false,
autoUpdatedAt: false,
attributes:
{
theme:
{
model: 'Theme',
required: true
}
}
}
I know how to define it statically:
in: ['something', 'something other']
I know how to call constants I defined in my constants.js file :
defaultsTo: function ()
{
return String(sails.config.constants.articleDefaultTheme);
}
But I would like to get all themes in my DB, to have a dynamic in validation. So, I wrote this :
theme:
{
model: 'Theme',
required: true,
in: function ()
{
Theme.find()
.exec(function (err, themes)
{
if (err)
{
return next({ error: 'DB error' });
}
else if (themes.length === 0)
{
return next({ error: 'themes not found' });
}
else
{
var theme_ids = [];
themes.forEach(function (theme, i)
{
theme_ids[i] = theme.theme_id;
});
return theme_ids;
}
});
}
}
But it's not working, I have always the "1 attribute is invalid" error. If I write them statically, or if I check in the beforeCreate method with another DB request, it works normally.
If I sails.log() the returned variable, all the themes ids are here.
I tried to JSON.stringify() the returned variable, and also to JSON.parse(JSON.stringify()) it. I also tried to convert the theme.theme_id as a string with the String() function, but nothing else...
What am I doing wrong? Or is it a bug?
You can also check my question here : Waterline GitHub issues
Models's configuration at your attributes scope at in field of course will throw an error, because it should not use a function, especially your function is not return anything, also if you force it to return something, it will return Promise that Theme.find()... did.
Try use different approach. There are exist Model Lifecycle Callbacks. You can use something like beforeCreate, or beforeValidate to manually checking your dynamic Theme, if it's not valid, return an error.
Or if it's achievable using standard DB relation, just use simple DB relation instead.

How to handle server side validation in Ember-Data 1.0.0

I'm using Ember 1.2.0 and the latest Ember Data Beta and wonder, how to handle server side errors (from API calls).
This question is quite similar, but it doesn't work.
At first, the becameInvalid method doesn't triggered. I'm using ember-validations (do I have to?)
My API sends an 422 status code and responses like that:
{"errors":{"name":["has already been taken"],"initial":["has already been taken"]}}
model.js
Docket.Customer = DS.Model.extend( Ember.Validations, {
name: DS.attr('string'),
initial: DS.attr('string'),
description: DS.attr('string'),
validations: {
name: {
presence: true
}
},
becameError: function() {
alert('there was an error!');
},
becameInvalid: function(errors) {
alert("Record was invalid because: " + errors);
}
});
controller.js
Docket.OrganizationCustomersController = Ember.ArrayController.extend({
actions: {
save: function () {
var customer = this.store.createRecord('customer');
customer.set('name', this.get('name'));
customer.set('initial', this.get('initial'));
customer.set('description', this.get('description'));
customer.save().then(function() {
console.log('jeah')
}, function() {
console.log('nooo')
});
}
}
});
The becameError method gets fired, but the becameInvalid method doesn't.
The second problem: even if the error is triggered, Ember.js adds the new record to the DOM. How can I prevent this behaviour?
Your errors json is ok, I think you are using the DS.RESTAdapter, and it doesn't implement the becameInvalid based in json with errors.
Just DS.ActiveModelAdapter have implemented in the moment, so I recommend you to change your adapter configuration to:
Docket.ApplicationAdapter = DS.ActiveModelAdapter;
In order to keep DS.RestAdapter, you can override its ajaxError method with the one from ActiveModelAdapter.
As for today the code, slightly adapted because some dependencies are needed, would be :
App.ApplicationAdapter = DS.RESTAdapter.extend({
// ... your own customizations,
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText),
errors = {};
if (response.errors !== undefined) {
var jsonErrors = response.errors;
Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
}
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
Obviously you have a chance here to adapt to your backend specifics: HTTP code (422 is not a standard one) and format.
Source :
http://discuss.emberjs.com/t/how-to-handle-failure-to-save-on-server/3789

Resources