My problem is how do I validate data. I don't know JS, so I tried do in this way:
function insert(item, user, request) {
if(typeof item.NamePlayer!=='empty') // in app default value is 'empty'
{
request.execute();
}
}
Does JS have a contain method on a table? For example I want a response to table 'NamePlayer' and not add an item with the same value.
Your condition will always be true. The operator typeof will return one of the following values: "number," "string," "boolean," "object," "function," and "undefined." - so it will never be "empty". If you want to check whether the item.NamePlayer is not empty, you can use the condition below:
if (item.NamePlayer !== '') {
// ...
}
You can also simplify the condition, which will also catch the case where the client didn't send a NamePlayer value in the input:
if (item.NamePlayer) {
// ...
}
One more thing: your script will only dealing with the "positive" case; it also needs to send a response in case the condition fails. Something like the code below:
function insert(item, user, request) {
if (item.NamePlayer) {
request.execute();
} else {
request.respond(400, 'NamePlayer is required');
}
}
Related
I have a string:
string = "abc_test_dashboard.json";
The value of string could vary like:
"tes.test.dashboard.json"
"jhgwefj-gfjh.widget.json"
The last "dashboard.json" and "widget.json" is static and could be either of them depending on a condition.
Basically I'm trying to identify if its "dashboard" or "widget" from the string.
I want to do stuff based on:
if ("dashboard.json") {//do some stuff}
else { // do something else
}
I also just realized that I may have multiple files with same name, and hence I may end up getting (1), (2) suffixes i.e: "abc_test_dashboard(1).json", "abc_test_dashboard(2).json". is there any way to test these kind of scenarios?
Thanks
You can do it with
if(string.endsWith('dashboard.json')) {
}
if(string.endsWith('widget.json')) {
}
Also you can use regex if you want (in case your target browsers do not support endsWith);
if (/widget\.json$/.test('widget.json')) {
}
Using regex you can even extract the initial portion of the file;
var widgetInfo = 'asd.widget.json'.match(/^(.*)widget\.json$/)
if (widgetInfo) {
console.log(widgetInfo[1]) // will print `asd.`
}
// similar code to check for `dashboard.json`
EDIT:
In the case you commented you can use the following regex; /^(.*)widget(\(.+\))?\.json$/. It will match strings in the forms of randomstring.widget.json and randomstring.widget(1).json, but not randomstring.widget().json
If you don't mind RegEx, you can use the String match() method as in the below:
function checkStrEnd(str) {
if (str.match(/dashboard\.json$/)) {
console.log('Do dashboard stuff');
} else if (str.match(/widget\.json$/)) {
console.log('Do widget stuff');
} else {
console.log('Do something else');
}
}
checkStrEnd('tes.test.dashboard.json'); // 'Do dashboard stuff'
checkStrEnd('jhgwefj-gfjh.widget.json'); // 'Do widget stuff'
checkStrEnd('random string'); // 'Do something else'
you can use includes to see if the string exists within the string
let arr = ["tes.test.dashboard.json", "jhgwefj-gfjh.widget.json"]
arr.forEach(item => {
if (item.includes('dashboard.json')) {
console.log('dasboard')
} else if (item.includes('widget.json')) {
console.log('widget')
}
})
How can I define some validation rules depending on some conditions in request body.
For example, I want to validate that post description field is set only if the post is published (isPublished flag equals true), something like:
module.exports = function(Post) {
if(req.body.isPublished === true) {
Post.validatesPresenceOf('description');
}
}
Simply, you can use options parameter
Post.validatesPresenceOf('description', {if: 'isPublished'});
Ref: #validatable-validatespresenceof
May be you are looking for something like this
Post.observe('before save',(ctx,next)=>{
//if post is created
if(ctx.isNewInstance) {
if(ctx.instance.isPublished)
Post.validatesPresenceOf('description');
}
//if post is updated
else{
if(ctx.data.isPublished)
Post.validatesPresenceOf('description');
}
return next();
})
I am trying to findOne document in my Template.admin.events code. I have a form and onClick I want to verify if the ID of the ObjectID entered is an existing document in my collection and fetch that result to show it on the template.
My event code on the client :
Template.admin.events({
'click #btnAjouterObjet'(event) {
let objetIdInput = $('#object_id').val().toString();
Meteor.subscribe('objetsFindOne', objetIdInput, {
onReady: function () {
let obj = Objets.findOne();
if (obj) {
console.log("found");
console.log(obj);
objetsArr.push(objetIdInput);
}
else {
console.log("not found");
console.log(obj);
}
}
});
}
});
In my Objets api :
Meteor.publish('objetsFindOne', function objetsFindOne(param_id){
return Objets.find({_id : param_id});
})
I have verified and my objetIdInput always change on click when a different Id is entered but the subscribe always returns the first id entered. I also added the onReady because otherwise it returned undefined.
I am new to Meteor and I have also tried to subscribe to all the collection and doing the find on the client but I don't think it is the best idea as my collection has about 22000 documents.
Just to elaborate a little bit on the first answer, as to how to change this pattern:
(1) you should place your Meteor.subscribe() call in your Template.admin.onCreated() function.
(2) the subscription reads from a reactive value, for example, new ReactiveVar().
(3) now, anytime the reactive value changes, the subscription will re-run. So, in your template event, you set the reactive value to the id and let the subscription handle the rest.
Discover Meteor and other resources should be helpful on any details.
You are going about this all wrong. I suggest you take a look at Template-Level Subscriptions
I opted for the use of a method :
Client side:
'click #btnAjouterObjet'(event) {
let objetIdInput = $('#object_id').val().toString();
let result = Meteor.call('findObj', objetIdInput, function (error, result) {
if (error) {
console.log(error.reason);
return;
}
console.log(result);
});
}
On the server side :
Meteor.methods({
findObj: function (param_id) {
console.log(Objets.find({ _id: param_id }).fetch());
return Objets.find({ _id: param_id }).fetch();
},
});
I have some code that exercises the “invalid values” setting on an element range index. In this case, I have configured a dateTime element range index on the onDate element in my database (which will apply to both XML elements and JSON properties). I’ve set that index to reject invalid values. This setting means if I try to set the value of an onDate element and it is not castable to a dateTime or is null (literal null in JSON or xsi:nil="true" in XML), my update will fail. (The opposite behavior is to completely ignore invalid values.)
I tried the following code in Server-Side JavaScript in MarkLogic 8.0-4:
'use strict';
declareUpdate();
var errors = [];
var inputs = {
'/37107-valid.json': (new Date()).toISOString(),
'/37107-invalid.json': 'asdf', // Should throw an error
'/37107-null.json': null
};
for(var uri in inputs) {
try {
xdmp.documentInsert(
uri,
{ 'onDate': inputs[uri] },
xdmp.defaultPermissions(),
['37107'] // Collections
);
} catch(err) {
errors.push(err);
}
}
errors.length;
I would have expected my request to succeed and to end up with 1 === errors.length, because only the second insert would have failed because 'asdf' is not castable as a dateTime and it is not null. However, instead I get an XDMP-RANGEINDEX error and my transaction fails. Why doesn’t my try/catch work here?
The issue is how MarkLogic processes update transactions. Rather than actually changing the data with each xdmp.docuentInsert(…) call, MarkLogic queues up all of the updates and applies them atomically at the end of the request. (This is also why you can’t see database updates within the same transaction.) Thus, the error isn’t being thrown until after the loop has executed and the database tries to commit the queued transactions. This behavior is the same in XQuery (slightly simplified):
let $uris := (
'/37107-valid.xml',
'/37107-invalid.xml',
'/37107-null.xml'
)
let $docs := (
<onDate>{fn:current-dateTime()}</onDate>,
<onDate>asdf</onDate>,
<onDate xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
)
return
for $uri at $i in $uris
return
try {
xdmp:document-insert($uri, $docs[$i], (), ('37107'))
} catch($err) {
xdmp:log($err)
}
In order to catch the errors synchronously, you’d need to put each update into its own transaction. In general, this approach will be much slower and resource intensive than MarkLogic’s default transaction handling. However, it’s illustrative here to demonstrate what’s happening under the covers and can come in handy for specific use cases, like this one.
In the example below, I use xdmp.invokeFunction() to “call” a function in a separate transaction from the parent request. (First-class functions for the win!) This allows the updates to be fully applied (or rolled back with an error) and the calling module to see the updates (or errors). I’ve wrapped the low-level xdmp.invokeFunction() in my own applyAs() function to provide some niceties, like correctly passing function arguments to the curried function.
'use strict';
var errors = [];
var inputs = {
'/37107-valid.json': (new Date()).toISOString(),
'/37107-invalid.json': 'asdf',
'/37107-null.json': null
};
var insert = applyAs(
function(uri, value) {
return xdmp.documentInsert(
uri,
{ 'onDate': inputs[uri] },
xdmp.defaultPermissions(),
['37107']
);
},
{ isolation: 'different-transaction', transactionMode: 'update' },
'one'
);
for(var uri in inputs) {
try {
insert(uri, inputs[uri]);
} catch(err) {
errors.push(err);
}
}
errors.length; // Correctly returns 1
// <https://gist.github.com/jmakeig/0a331823ad9a458167f6>
function applyAs(fct, options, returnType /* 'many', 'one', 'iterable' (default) */) {
options = options || {};
return function() {
var params = Array.prototype.slice.call(arguments);
// Curry the function to include the params by closure.
// xdmp.invokeFunction requires that invoked functions have
// an arity of zero.
var f = (function() {
return fct.apply(null, params);
}).bind(this);
// Allow passing in user name, rather than id
if(options.user) { options.userId = xdmp.user(options.user); delete options.user; }
// Allow the functions themselves to declare their transaction mode
if(fct.transactionMode && !(options.transactionMode)) { options.transactionMode = fct.transactionMode; }
var result = xdmp.invokeFunction(f, options); // xdmp.invokeFunction returns a ValueIterator
switch(returnType) {
case 'one':
// return fn.head(result); // 8.0-5
return result.next().value;
case 'many':
return result.toArray();
case 'iterable':
default:
return result;
}
}
}
I have a web page in which when a user clicks on a specific element, a javascript function is triggered which uses $.post() (i.e. jquery) to send the user's data to a PHP script which modifies a database.
On success, the PHP page simply prints
<p id='success'>Yay!</p>
On fail, it prints:
<p id='failure'>$some_error_message</p>
The callback part of the $.post then checks which of these exists. On success, it simply shows an existing (currently hidden) element. On failure, I want to grab the $some_error_message bit, and put it on my page.
I've found a way to do this (as below) but it's clunky - I am sure I shouldn't be having to use an ".each" function when I only want to access a single element. Is there a better way of doing this?
$.post('myURL.php', myData, function(retData)
{
if ( $(retData).filter('#success') )
{
$('#mySuccessDiv').show(200);
}
else if ($(retData).filter('#failure') )
{
$(retData).filter('#failure').each(function()
{
$('#myErrorDiv').html($(this).html());
});
}
else
$('#myErrorDiv').html("Unspecified Error");
}, "html");
As I say, the use of .each seems wasteful, but I can't simply use
$('#myErrorDiv').html($(retData).filter('#failure').html());
because .filter returns a series of objects. But equally, I can't work out how to access only element 0 (since I'm filtering on ID, there can only be one match). I tried:
$('#myErrorDiv').html($(retData).filter('#failure')[0].html());
but it didn't like that.
Am I forced to use .each, or am I being really obtuse?
.filter() will return a jQuery object(with or without any element), so it will always be truthy, to see whether it returned any element you need to check the length of the returned jQuery object
$.post('myURL.php', myData, function (retData) {
var $obj = $(retData);
if ($obj.filter('#success').length) {
$('#mySuccessDiv').show(200);
} else if ($obj.filter('#failure').length) {
$('#myErrorDiv').html($obj.html());
} else {
$('#myErrorDiv').html("Unspecified Error");
}
}, "html");
Another solution is to use .is()
$.post('myURL.php', myData, function (retData) {
var $obj = $(retData);
if ($obj.is('#success')) {
$('#mySuccessDiv').show(200);
} else if ($obj.is('#failure')) {
$('#myErrorDiv').html($obj.html());
} else {
$('#myErrorDiv').html("Unspecified Error");
}
}, "html");