How to control document do not get or add additional property in loopbak? - mongodb

I have a registration model in loopback over mongodb with fallowing properties:
"properties": {
"Fname": {
"type": "string",
"required": true
},
"Lname": {
"type": "string",
"required": true
},
"phone": {
"type": "string",
"required": true
},
"date": {
"type": "string",
"required": true
},
"time": {
"type": "string",
"required": true
}
}
in application I post some additional data with model required data, for controlling and processing in server side:
submitForm() {
let headers = new Headers(
{
'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
let data = JSON.stringify({
Fname: this.form.Fname,
Lname: this.form.Lname,
phone: this.form.phone,
time: this.form.time,
date: this.form.date,
uid: this.form.uid
});
//console.log(data);
let url = 'http://localhost:3000/api/registrations';
return new Promise((resolve, reject) => {
this.http.post(url, data, options)
.toPromise()
.then((response) => {
console.log('API Response : ', response.status);
resolve(response.json());
})
.catch((error) => {
console.error('API Error : ', error.status);
console.error('API Error : ', JSON.stringify(error));
reject(error.json());
});
});
}
In server side I have this code:
Registration.observe('before save', function (ctx, next) {
if (ctx.instance) {
// When Create (POST)
// ctx.instance have the json properties
console.log("Triggers when create");
if (checkUID(ctx.instance) ==200 ){
console.log('ok');
}
} else {
// When Update (UPDATE)
// ctx.data have the json properties
console.log("Triggers when update");
}
next();
});
but after successfully registration I saw that uid that was added into document and regardless to model's properties, document contains addition properties.
{
"Fname": "Eram",
"Lname": "SA",
"phone": "1234567890",
"date": "2017/10/06",
"time": "17:37:46",
"id": "59d78e3f5e5e6704205038aa",
"uid": "38bc3241a43073a7b40d186f24923cc5"
},

Related

How would you find a certain map entry by a specific value?

Given the following map:
"user":
{
"userid":0,
},
"appData":{
"title":"Test",
"pages":1,
"posts":[
{
"postid":27979530,
"text":Test,
},
{
"postid":7732445,
"text":Test123,
},
{
"postid":9463254,
"text":Test568,
},
]
}
Given that map I want to try to find the entry for postid 7732445 so I can return the text value of Test123
What is the best way of doing something like that?
Given that
final Map<String, dynamic> json = {
"user": {
"userid": 0,
},
"appData": {
"title": "Test",
"pages": 1,
"posts": [
{
"postid": 27979530,
"text": "Test",
},
{
"postid": 7732445,
"text": "Test123",
},
{
"postid": 9463254,
"text": "Test568",
},
]
}
};
you could do this search by doing
json["appData"]["posts"]
.firstWhere(
(item) => item["postid"] == 7732445,
orElse: () => <String, Object>{},
)["text"]
Because of the orElse, this will return null if not found.

PayPal Integration and payment status in react native

I'm trying to integrate PayPal as a payment method in my react-native app. I get an access token by hitting https://api.sandbox.paypal.com/v1/oauth2/token API, but when I'm trying to pass access token to payment API https://api.sandbox.paypal.com/v1/payments/payment got response with status code 400 or 500 both are varying.
My code is
let currency = '100 INR'
currency.replace("INR", "")
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
this.setState({accessToken:data.access_token})
// console.log(JSON.stringify(dataDetail))
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(this.state.accessToken)
},
body:dataDetail
}
)
.then(response => {
console.log('response=====',response)
// const { id, links } = response.data
// const approvalUrl = links.find(data => data.rel == "approval_url")
// this.setState({
// paymentId: id,
// approvalUrl: approvalUrl.href
// })
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
}
)
Any one can help please ?
response
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "f2d967a5-2700-4f03-b2ac-2e4ec22f10e4", "offset": 0, "size": 232}}, "bodyUsed": false, "headers": {"map": {"cache-control": "max-age=0, no-cache, no-store, must-revalidate", "content-language": "*", "content-length": "232", "content-type": "application/json", "date": "Tue, 23 Feb 2021 07:20:25 GMT", "paypal-debug-id": "27bb91ae40c3a"}}, "ok": false, "status": 400, "statusText": undefined, "type": "default", "url": "https://api.sandbox.paypal.com/v1/payments/payment"}
reference Link PAYPAL INTEGRATION IN REACT-NATIVE
https://api.sandbox.paypal.com/v1/payments/payment
v1/payments is a deprecated API. You should integrate the current v2/checkout/orders instead.
Here is some documentation -- you want "Create Order" and "Capture Order" API calls.
But, if you want to understand the problems with your v1 code, here they are fixed and with proper request+response data logging
Issues:
currency variable wasn't being set to a valid number w/o spaces
You need to JSON.stringify() your request body.
<script>
let currency = '100 INR';
currency = currency.replace("INR", "").trim() ; //this was a problem line, replace() is not in-place. And also extra space to trim
let accessToken = '';
const dataDetail = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"transactions": [{
"amount": {
"total": currency,
"currency": "INR",
"details": {
"subtotal": currency,
"tax": "0",
"shipping": "0",
"handling_fee": "0",
"shipping_discount": "0",
"insurance": "0"
}
}
}],
"redirect_urls": {
"return_url": "https://example.com",
"cancel_url": "https://example.com"
}
}
fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Accept-Language': 'en_US',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('AUrtJxcHfMUlDjHgV2FHMOUnzMkUeu86_km7h67uEHzH5b5RN7Vo-q8AYPtcdz7Iaioc46xW0H9JQZmT:EMbbJ-YqQLT6liuPtJURq2pAgh9WuUTDKmV355_VIeADst0BMlnUNKiHVLK7itCyZFXrEQOex9p93WO8')
},
body: 'grant_type=client_credentials'
}).then(response => response.json())
.then(async (data) => {
console.log(data.access_token)
accessToken=data.access_token
// console.log(JSON.stringify(dataDetail))
let createRequest = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+(accessToken)
},
body:JSON.stringify(dataDetail)
}
console.log('Request body string',createRequest.body);
console.log('Request body (formatted)', JSON.stringify( JSON.parse(createRequest.body) ,null,4) );
fetch ('https://api.sandbox.paypal.com/v1/payments/payment',createRequest
)
.then(function(response) {
console.log('Response object', response);
return response.json()
})
.then(async(data) => {
console.log('Response data',data);
console.log('Response data (formatted)', JSON.stringify(data,null,4) );
}).catch(err => {
console.log({ ...err })
})
}).catch(function (error) {
let edata = error.message;
console.log('Error:', edata)
})
</script>

Promises do not work (for me)

Probably I'm missing something basic here. Scenario goes like this:
Within the root view controller of my application (App.controller.js, onInit function) I'm performing a series of read operations on a named model in order to have additional data ready mainly for use by formatters in subsequent views. What I have done is using promises to make sure that data will be ready.
Problem is that application occasionally crashes when the initial view with pattern "" (Worklist.view.xml in my case) is loaded after the root view (App.view.xml) because the formatter function can't find the data expected. Added a few break-points and observed the debugger:
stopping at the first read function
stopping at the promises condition at the end
stopping (and throwing error) at the formatter function at the subsequent view
stopping in the success function of oData read (resolve)
page freezes afterwards as result of the exception thrown above
"Normal" flow, when application doesn't crash goes like this:
stopping at the first read function
stopping at the promises condition at the end
stopping in the success function of oData read (resolve)
stopping at the readyToGo function (it's there just for temporary debugging)
stopping at the formatter function at the subsequent view
page display, everything in order
Judging by the above, I have reached the conclusion that my promises do not work. Any ideas?
sap.ui.define([
"kristal/apps/agreements/controller/BaseController",
"sap/ui/model/json/JSONModel"
], function (BaseController, JSONModel) {
"use strict";
/* PROMISE VARIABLES */
var oModelTypeDataDeferred = jQuery.Deferred();
var oModelStatusDataDeferred = jQuery.Deferred();
var oModelRoleDataDeferred = jQuery.Deferred();
var oModelRefDataDeferred = jQuery.Deferred();
var oModelExtOrgDataDeferred = jQuery.Deferred();
var oModelInvolvementDataDeferred = jQuery.Deferred();
return BaseController.extend("kristal.apps.agreements.controller.App", {
onInit: function () {
/* CALLED AFTER PROMISES HAVE BEEN FULFILLED */
var readyToGo = function() {
jQuery.sap.log.error("Ready!");
};
var oViewModel;
var fnSetAppNotBusy;
var iOriginalBusyDelay = this.getView().getBusyIndicatorDelay();
var oViewModel = new JSONModel({
busy: true,
delay: 0
});
this.setModel(oViewModel, "appView");
fnSetAppNotBusy = function() {
oViewModel.setProperty("/busy", false);
oViewModel.setProperty("/delay", iOriginalBusyDelay);
};
this.getOwnerComponent().getModel().metadataLoaded().then(fnSetAppNotBusy);
var oModel = this.getOwnerComponent().getModel("f4");
/* oData READ OPS */
oModel.metadataLoaded().then(function(){
// Initialize additional data
var sPath = "/Agreement_TypesSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelTypeDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
sPath = "/Agreement_StatusesSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelStatusDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
sPath = "/Role_TypesSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelRoleDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
sPath = "/Reference_TypesSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelRefDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
sPath = "/External_OrganizationsSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelRefDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
sPath = "/Involvement_TypesSet";
oModel.read(sPath, {
success: function(oData, oResponse) {
oModelInvolvementDataDeferred.resolve();
},
error: function(oError) {
jQuery.sap.log.error("Error", oError);
}
});
/* IF ALL PROMISES FULFILLED, PROCEED */
jQuery.when(oModelTypeDataDeferred, oModelStatusDataDeferred, oModelRoleDataDeferred, oModelRefDataDeferred, oModelExtOrgDataDeferred, oModelInvolvementDataDeferred)
.done().then(jQuery.proxy(readyToGo, this));
},
// ...
});
});
manifest.json:
{
"_version": "1.4.0",
"sap.app": {
"id": "kristal.apps.agreements",
"type": "application",
"i18n": "i18n/i18n.properties",
"title": "{{appTitle}}",
"description": "{{appDescription}}",
"applicationVersion": {
"version": "1.0.0"
},
"dataSources": {
"mainService": {
"uri": "/DEV/sap/opu/odata/SAP/ZCONTRACTS_SRV/",
"type": "OData",
"settings": {
"odataVersion": "2.0",
"localUri": "localService/metadata.xml"
}
}
},
"sourceTemplate": {
"id": "sap.ui.ui5-template-plugin.1worklist",
"version": "1.38.3"
}
},
"sap.ui": {
"technology": "UI5",
"icons": {
"icon": "sap-icon://task",
"favIcon": "",
"phone": "",
"phone#2": "",
"tablet": "",
"tablet#2": ""
},
"deviceTypes": {
"desktop": true,
"tablet": true,
"phone": true
},
"supportedThemes": [
"sap_hcb",
"sap_bluecrystal"
]
},
"sap.ui5": {
"rootView": {
"viewName": "kristal.apps.agreements.view.App",
"type": "XML",
"id": "app",
"async": true
},
"dependencies": {
"minUI5Version": "1.38.0",
"libs": {
"sap.ui.core": {
"minVersion": "1.38.0"
},
"sap.m": {
"minVersion": "1.38.0"
},
"sap.ushell": {
"minVersion": "1.38.0"
},
"sap.collaboration": {
"minVersion": "1.38",
"lazy": true
}
}
},
"contentDensities": {
"compact": true,
"cozy": true
},
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "kristal.apps.agreements.i18n.i18n"
}
},
"": {
"dataSource": "mainService",
"preload": true,
"settings": {
"defaultBindingMode": "TwoWay"
}
},
"f4": {
"dataSource": "mainService",
"preload": true,
"settings": {
"metadataUrlParams": {
"sap-documentation": "heading"
},
"defaultBindingMode": "TwoWay"
}
}
},
"routing": {
"config": {
"routerClass": "sap.m.routing.Router",
"viewType": "XML",
"viewPath": "kristal.apps.agreements.view",
"controlId": "app",
"controlAggregation": "pages",
"bypassed": {
"target": [
"notFound"
]
},
"async": true
},
"routes": [{
"pattern": "",
"name": "worklist",
"target": [
"worklist"
]
}, {
"pattern": "AgreementsSet/{objectId}",
"name": "object",
"target": [
"object"
]
}],
"targets": {
"worklist": {
"viewName": "Worklist",
"viewId": "worklist",
"viewLevel": 1
},
"object": {
"viewName": "Object",
"viewId": "object",
"viewLevel": 2
},
"objectNotFound": {
"viewName": "ObjectNotFound",
"viewId": "objectNotFound"
},
"notFound": {
"viewName": "NotFound",
"viewId": "notFound"
}
}
}
},
"sap.platform.abap": {
"uri": "/sap/bc/ui5_ui5/sap/zctr_contr_mnt/webapp",
"_version": "1.1.0"
}
}
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/Device",
"kristal/apps/agreements/model/models",
"kristal/apps/agreements/controller/ErrorHandler"
], function(UIComponent, Device, models, ErrorHandler) {
"use strict";
return UIComponent.extend("kristal.apps.agreements.Component", {
metadata: {
manifest: "json"
},
init: function() {
UIComponent.prototype.init.apply(this, arguments);
this._oErrorHandler = new ErrorHandler(this);
this.setModel(models.createDeviceModel(), "device");
this.setModel(models.createFLPModel(), "FLP");
this.getRouter().initialize();
},
destroy: function() {
this._oErrorHandler.destroy();
// call the base component's destroy function
UIComponent.prototype.destroy.apply(this, arguments);
},
getContentDensityClass: function() {
if (this._sContentDensityClass === undefined) {
// check whether FLP has already set the content density class; do nothing in this case
if (jQuery(document.body).hasClass("sapUiSizeCozy") || jQuery(document.body).hasClass("sapUiSizeCompact")) {
this._sContentDensityClass = "";
} else if (!Device.support.touch) { // apply "compact" mode if touch is not supported
this._sContentDensityClass = "sapUiSizeCompact";
} else {
// "cozy" in case of touch support; default for most sap.m controls, but needed for desktop-first controls like sap.ui.table.Table
this._sContentDensityClass = "sapUiSizeCozy";
}
}
return this._sContentDensityClass;
}
});
});
It was all about moving functionality from the root view to component.js and putting the router initialization into the promise conditions, thank you experts

how to access postgresql database view using strongloop

Please help in accessing postgresql database view using strongloop.
im able to access table
{"name": "test",
"options": {
"idInjection": false,
"postgresql": {
"schema": "public",
"table": "test_data_v"
}
},
"properties": {
"assetid": {
"type": "String",
"required": false,
"length": 40,
"precision": null,
"scale": null,
"id": 1,
"postgresql": {
"columnName": "asset_id",
"dataType": "character varying",
"dataLength": 40,
"dataPrecision": null,
"dataScale": null,
"nullable": "YES"
}
}
}}
in same way please suggest me how to access view
Thanks
Divya
I am not installed postgresql but I tried in mysql, Its working fine.
IN your model you can do directly see this Example
In database I have created view that is
CREATE VIEW shareviews AS
SELECT id,name
FROM share where id = 1;
In model you can call viewname directly like this example
module.exports = function(Share) {
var server = require('../../server/server');
var ds = server.dataSources.MySQL; // use server.dataSources.postgres;
Share.list = function(optionalparam, cb) {
var sql = 'select * from shareviews';
ds.connector.execute(sql, function(err, data)
{
if(err) return err;
console.log(err);
console.log("data",data);
cb(null, data);
});
}
Share.remoteMethod(
'list',
{
accepts: {arg: 'param', type: 'string'},
returns: {arg: 'result', type: 'object'},
http: {path: '/list', verb: 'get'}
}
);
};
You need to set data source in datasource.json
{
"db": {
"name": "db",
"connector": "memory"
},
"postgres": {
"host": "localhost",
"port": 5432,
"database": "postgres",
"username": "postgres",
"password": "*******",
"name": "postgres",
"connector": "postgresql"
}
}
Then in model-config.json you need to assign data source name to each
model.
That is
{
"_meta": {
"sources": [
"loopback/common/models",
"loopback/server/models",
"../common/models",
"./models"
],
"mixins": [
"loopback/common/mixins",
"loopback/server/mixins",
"../common/mixins",
"./mixins"
]
},
"User": {
"dataSource": "db"
},
"AccessToken": {
"dataSource": "db",
"public": false
},
"ACL": {
"dataSource": "db",
"public": false
},
"RoleMapping": {
"dataSource": "db",
"public": false
},
"Role": {
"dataSource": "db",
"public": false
},
"yourmodelname": {
"dataSource": "postgres",
"public": true
},
"yourmodelname": {
"dataSource": "postgres",
"public": true
}
}
then you can access database in you model.js or Rest call(example localhost:3000/explorer) For Example my
model name Grocerylist
module.exports = function(Grocerylist) {
Grocerylist.beforeRemote('create', function(context, user, next) {
var req = context.req;
req.body.date = Date.now();
req.body.shopperId = req.accessToken.userId;
next();
});
Grocerylist.complete = function(shopperId, cb) {
Grocerylist.find({
where: {
purchased:false,
shopperId: shopperId,
}
}, function(err, list) {
var response;
if (typeof list === 'undefined' || list.length === 0) {
response = "All done shopping!"
}
else {
response = "Shopping is not done.";
}
cb(null, response);
});
};
Grocerylist.remoteMethod(
'complete',
{
accepts: {
arg: 'shopperId', type: 'string'
},
http: {
path: '/complete',
verb: 'get'
},
returns: {
arg: 'complete',
type: 'string'
}
}
);
};

Add event to calendar on SharePoint through REST API

I'm trying to add a calendar event to a SharePoint Calendar through REST API but i can't seems to find the relevant resources to achieve this.
If i understand correctly, the calendar in SharePoint is a List of events object, as such I should be able to add the event via ListItem object?
Sorry if this sounds wrong as I'm not familiar with SharePoint structure.
Thanks
This is the example for OAuth token Authentication but REST part is anyway like this.
var dataObj = {
"Subject": "Birthday Party"
"Body": {
"ContentType": "Text",
"Content": "Birthday Party for Cathy",
},
"Start": {
"dateTime": "2016-07-03T09:00:00Z",
"timeZone": "Asia/Tokyo"
},
"End": {
"dateTime": "2016-07-04T11:00:00Z",
"timeZone": "Asia/Tokyo"
},
"Location": {
"DisplayName": "Conference Room 1"
},
"ShowAs": "Busy",
"Attendees": [
{
"EmailAddress": { "Name": "Alex Darrow", "Address": "darrow.alex#company.com" },
"Type": "Required"
}
]
};
var url = "https://graph.microsoft.com/v1.0/me/events/";
var data = JSON.stringify(dataObj);
$.ajax({
url: url,
type: "POST",
data: data,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json;odata.metadata=full;odata.streaming=true");
XMLHttpRequest.setRequestHeader('Authorization', 'Bearer ' + accessToken);
XMLHttpRequest.setRequestHeader("content-type", "application/json;odata=verbose");
},
success: function (result, textStatus, jqXHR) {
//Success
},
error: function (data) {
//
}});