Set Batch off just for a group of requests - sapui5

i have a question is there a way to set for consecutive request the batchmodus off? i can set it on the modelbase but than it is deactivated overall -> thats not what i want, just for these example of requests. Why? because we have lagacy code in the backend and there is a commit, commit and batch does not like each other o.o
e.g. => thats just a coded example.
oData.forEach(element => {
if (element.isSelected) {
if (!bValidationError) {
oTCGW.create("/TestSet('" + element.test + "')/L", L, {
useBatch: false,
success: function (oData) {
oTCGW.create("/TestSet2('" + element.no + "')/C", C, {
useBatch: false,
success: function (oData2) {
oTCGW.callFunction("/TestFunc", {
useBatch: false,
method: "POST",
urlParameters: {
no: element.no,
name: name,
plate: plate
},
success: function (osuccess) {
that.oParentController._readDataFromBackendFull();
that.onPressExit();
},
error: function (oerror) {
}
});
},
error: function (odata2) {
}
});
},
error: function (oData) {
}
});

Related

Fastify validate schema with yup - schema.validateSync is not a function

From the Fastify documentation in the section titled Using other validation libraries I'm trying to get yup to validate my schema but I keep getting schema.validateSync is not a function and I don't know why??
I want the schema to still be valid for creating the swagger document but I want to use yup to give me the validation I need.
const yup = require("yup");
const yupOptions = {
strict: false,
abortEarly: false,
stripUnknown: true,
recursive: true,
};
async function isUsernameAvailable(fastify: any, _options: Object) {
const users = fastify.mongo.db.collection("users");
fastify.get(
"/api/v1/onboarding/isUsernameAvailable/:username",
{
schema: {
params: {
type: "object",
properties: {
username: { type: "string", maxLength: 12, minLength: 1 },
},
required: ["username"],
},
response: {
200: {
type: "object",
properties: {
available: {
type: "boolean",
description: "Returns true if username is available",
},
},
},
},
},
validatorCompiler: ({ schema, method, url, httpPart }: any) => {
return function (data: any) {
try {
const result = schema.validateSync(data, yupOptions);
return { value: result };
} catch (e) {
return { error: e };
}
};
},
},
async (request: any, _reply: any) => {
const { username } = request.params;
const foundNUsernames = await users.countDocuments(
{ username },
{ limit: 1 }
);
const available: boolean = foundNUsernames === 0;
return { available };
}
);
}
export { isUsernameAvailable };
if I use the below, the validation works but the swagger doc doesn't build
schema: {
params: yup.object({
username: yup.string().lowercase().max(12).min(1).required(),
}),
}
if I remove the validatorCompiler then I get no errors, swagger does build but I cant use yup
validatorCompiler: ({ schema, method, url, httpPart }: any) => {
return function (data: any) {
try {
const result = schema.validateSync(data, yupOptions);
return { value: result };
} catch (e) {
return { error: e };
}
};
},
}
how can I satisfy both?
Why do I want to use yup? I want to validate emails and transform values into lowercase.

Angular-datatables server-side processing and Buttons extension. data is empty

use Angular4 and angular-datatables.
Everything looks fine (pagination, column sorting, export buttons), but when I try to print/copy/export a table, it only outputs the headers, even though the rest of the data is there.
Any ideas what's should I check?
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 20,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
this.service.getServerSidePaganated(dataTablesParameters).subscribe(resp => {
that.cdrs = resp.data;
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [
{ data: 'source' },
{ data: 'destination' },
{ data: 'dateTime'},
{ data: 'callTime'},
{ data: 'timeOnHold'},
{ data: 'disposition'},
{ data: 'recordingFileName'}
],
// Declare the use of the extension in the dom parameter
dom: 'Bfrtip',
// Configure the buttons
buttons: [
'print',
'excel'
]
};
}
you should set the callback data
ajax: (dataTablesParameters: any, callback) => {
this.service.getServerSidePaganated(dataTablesParameters).subscribe(resp => {
// that.cdrs = resp.data; // remove this line
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: resp.data // set data
});
});

Hosting a Forge Autodesk viewer on Github

I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.

Setting params in Kendo UI Grid when calling a rest service [Workaround]

I have a Kendo UI Grid that is calling a rest service. It works fine, as long as I do not try to use any params.
I know the the rest service is correct, as I can call it from a browser, and get correct results [depending on the param I send]. Also, when I look the server log I see that it is calling the rest service with no params.
My code is below:
document).ready( function() {
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
filter: {field: "status", value: "2" }
dataType: "json",
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true,
});
I still cannot get this to work and am a bit stumped.
I have two rest services, one returns all data, one takes "status" as a part and return a subset of the data that equals the parm.
The URL is:
http://localhost/scoApps/PC/PCApp.nsf/rsPC.xsp/PCByStatus?status=2
When entered into browser I get the correct number of records.
So I changed the code (see below). I have included all of the code for the CSJS:
$(document).ready( function() {
// Double Click On row
$("#grid").on(
"dblclick",
" tbody > tr",
function() {
var grid = $("#grid").data("kendoGrid");
var row = grid.dataItem($(this));
window.location.replace("xpFormPC.xsp" + "?key=" + row.unid + "target=_self");
});
// Add hover effect
addExtraStylingToGrid = function() {
$("table.k-focusable tbody tr ").hover( function() {
$(this).toggleClass("k-state-hover");
});
};
// Search
$("#search").keyup( function() {
var val = $('#search').val();
$("#grid").data("kendoGrid").dataSource.filter( {
logic : "or",
filters : [ {
field : "serialNumber",
operator : "contains",
value : val
}, {
field : "officeLoc",
operator : "contains",
value : val
}, {
field : "model",
operator : "contains",
value : val
} ]
});
});
var crudServiceBaseUrl = "rsPC.xsp",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/PCByStatus",
dataType: "json"
},
update: {
url: crudServiceBaseUrl + "/PC/Update",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl + "/PC/Destroy",
dataType: "json"
},
create: {
url: crudServiceBaseUrl + "/PC/Create",
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status"
options.value = "2"
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
scrollable: {
virtual: true
},
height: 543,
schema: {
model: {
id: "PCId",
fields: {
PCId: {type:"string"},
serialNumber: {type: "string"},
officeLoc: {type: "string"},
unid: {type:"string"},
model: {type:"string"},
checkInDate: {type: "string"}
}
}
}
});
// Grid
grid = $("#grid").kendoGrid( {
dataSource: dataSource,
columns : [ {
field : "serialNumber",
title : "Serial Number"
}, {
field : "model",
title : "Model"
}, {
field : "officeLoc",
title : "Office Location"
}, {
field : "checkInDate",
title : "Check In Date",
template: "#= kendo.toString(kendo.parseDate(checkInDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
} ],
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataBound : addExtraStylingToGrid,
reorderable : true,
filterable : true,
scrollable : true,
selectable : true,
sortable : true
});
// Edit
function onEdit(e) {
}
// Change
function onChange(args) {
var model = this.dataItem(this.select());
ID = model.ID;
}
;
});
What am I doing wrong?
=========================================
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Now I just construct the URL I want. Not so elegant I suppose, but it works.
I have a workaround. Or possibly this is the way it is supposed to be done.
var crudServiceBaseUrl = "rsPC.xsp", dataSource = new kendo.data.DataSource(
{
transport : {
read : {
url : crudServiceBaseUrl
+ "/PCByStatus?status=2",
dataType : "json"
},
Filter is used for client side data unless you set serverFiltering to true.
Here is the filter kendo documentation and the serverFiltering documentation.
I use parameterMap when I need to send parameters that are not created by filtering the control that I'm using. The kendo documentation provides an example using parameterMap.
Here is an example of how I've used it in the past:
var appsDataSource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "App"
},
parameterMap: function (data, action) {
if (action === "read") {
data.lobid = lobId;
data.parent = isParent;
return data;
} else {
return data;
}
}
}
});
Try changing the parameterMap:
parameterMap: function(options, operation) {
if (operation == "read"){
options.field = "status";
options.value = "2";
return options;
}
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
and update the read definition to remove filter. One thing to consider is that you are not returning anything from the read method if it doesn't meet the criteria of not being a read and options is not null. That leaves out any other combination that isn't obviously handled in your existing code.

extjs4 proxy rest multiple request issue

Hi I am encountering a wierd behavior with my application:when I modify an item and then my proxy doas a put request, the first time is ok, the second time it sends two requests: the first with the data of the previous one, the second one with the actual data, the third time it sends three requests, onmy system it is not a big issue, because at end I get the right value on my database, but on my customer's system the result it is not always correct. Then I would like to remove this behavior.
this is my store:
Ext.create('Ext.data.Store',
{
storeId: 'bbCompaniesStore',
model:'Company',
pageSize: pageSize,
proxy:
{
idProperty : '_id',
type: 'rest',
url: 'data/companies/',
autoload: true,
noCache: true,
sortParam: undefined,
actionMethods:
{
create : 'PUT',
read : 'GET',
update : 'POST',
destroy: 'DELETE'
},
reader:
{
type: 'json',
root: 'data',
totalProperty: 'total'
},
},// proxy
listeners: {
exception: function(proxy, response, operation) {
Ext.gritter.add({
title: MongoVision.text['action.' + operation.action] || operation.action,
text: (operation.error ? operation.error.statusText : null) || MongoVision.text.exception
});
// Ext JS 4.0 does not handle this exception!
switch (operation.action) {
case 'create':
Ext.each(operation.records, function(record) {
record.store.remove(record);
});
break;
case 'destroy':
Ext.each(operation.records, function(record) {
if (record.removeStore) {
record.removeStore.insert(record.removeIndex, record);
}
});
break;
}
}
}
}
);
this is my model:
Ext.define('Company',
{
extend: 'Ext.data.Model',
fields: [
{
name : 'id',
type : 'string'
},
{
name :'firm',
type : 'string',
allowBlank: false
},{
name : 'p'
},
{
name: 'linee'
},
{
name : 'c'
},
{
name : 'data',
type: 'date'
},
{
name :'note'
},
{
name :'paese'
},
{
name : 'email'
},
{
name : 'telefono'
},
{
name : 'type'
},
{
name : 'website'
},
{
name : 'session_id'
},
{
name : 'group_id'
}
],
proxy : {
type : 'rest',
url : 'data/companies/'
}
}
);
after googling around I found a similar issue for extjs3, with no solution, I think it is strange that after so long time, there is no yet a solution; it should work now
I faced the same issue, resolved it by simply passing
batchActions: true when creating the Proxy. The default behavior for 'rest' proxies is to turn off batching.... (See extjs/src/data/proxy/Rest.js)