I want to make my form submission happen server-side in order to not expose my API key. I plan to do this with netlify functions however I don't know how that would look with Axios. I've looked for examples on how to do this but I don't seem to find any. Could some help me I'm stuck as to what to put inside my the Netlify function? If anyone has worked with these two programs and could provide a hand that would be helpful here is my javascript with my submission function.
var form = document.querySelector("#user_form");
let reqHeaders = {
headers: {
Authorization: "Bearer",
}
}
let url = ""
let reqData = {
records: [
{
fields: null
}
]
}
let formData = {
firstName: "",
lastName: "",
email: ""
}
function logData(id, dataObj, value) {
dataObj[id] = value;
console.log(value)
}
function formMessg (id) {
document.querySelector(id).style.display = "block";
setTimeout(function(){
document.querySelector(id).style.display = "none";
form.reset();
}, 2500)
}
form.addEventListener("submit", function (e) {
e.preventDefault();
let spam = document.getElementById('spam').value;
try {
for(const data in formData){
if(formData[data] === "" || spam.length !== 0){
const error = new Error();
error.notVaild = true;
throw error;
}
}
reqData.records[0].fields = formData;
console.log(reqData);
axios.post(url, reqData, reqHeaders).then((res) => {
formMessg ('.success-messg');
form.style.display = "none";
})
.catch ((err) => {
throw err;
});
} catch (err){
if (err.reponse){
formMessg ('.fail-messg');
} else if (err.request) {
formMessg ('.fail-messg');
} else if ("Notvalid") {
formMessg ('.fill-messg');
}else {
console.log(err);
}
}
});
Related
I have the following code
#Injectable()
export class ReceptionService {
private generalInfoDataSrc$ = new BehaviorSubject<any>(null);
public generalInfoData = this.generalInfoDataSrc$.asObservable();
setGeneralInfo(dataSrc: GeneralInfoMModal) {
this.generalInfoDataSrc$.next(dataSrc);
}
}
From my component1 I will set the above as
OnSelect(patient: any) {
let generalInfo = new GeneralInfoMModal();
generalInfo.id = patient.id;
// some other code here
// this.recepService.setGeneralInfo(generalInfo);
}
// from component2
//
ngOnInit() { getPatientDetails() }
getPatientDetails() {
this.receptionService.generalInfoData.pipe(mergeMap(response => {
if (response && response.id) {
this.loading = true;
return this.receptionService.get('User/Get' + response.id, this.sourceobj);
} else {
return of(null);
}
}), takeUntil(this.unsubscribe$)).subscribe(response => {
this.patient = response;
this.loading = false;
}, error => {
this.loading = false;
// this.utility.showMsg('An error occurred while getting user.')
}, () => {
})
}
Every things works well. I keep on selecting a user thereby calling the User/Get api. But if in case if the api returns an error then error part is executed after which when there is a change in behaviorsubject(user is selected) it doesn't call the User/Get. Is there other way of handling errors with behaviorsubject or any other approach to handle the idea. How a behaviorsubject should be used in such a case.
If you are using the same behavior subject over and over again, and if there is an error, you need to set the behavior subject back to null, so that when the next user is set, it will get the latest value.
Try something like this:
getPatientDetails() {
this.receptionService.generalInfoData.pipe(mergeMap(response => {
if (response && response.id) {
this.loading = true;
return this.receptionService.get('User/Get' + response.id, this.sourceobj);
} else {
return of(null);
}
}), takeUntil(this.unsubscribe$)).subscribe(response => {
this.patient = response;
this.loading = false;
}, error => {
this.loading = false;
///////////////////////////////// ADD THIS LINE ///////////////////////
this.recepService.setGeneralInfo(null);
// this.utility.showMsg('An error occurred while getting user.')
}, () => {
})
Here's my Angular controller
//Save And Update
$scope.AddUpdateBusinessType = function() {
var businessType = {
Code: $scope.businessCode,
BusiType: $scope.businessType
};
var getBusinessTypeAction = $scope.BusinessTypeAction;
if (getBusinessTypeAction == "Update") {
businessType.BusinessTypeId = $scope.businessTypeId;
var getBusinessTypeData = businessTypeService.updateBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Updated Successful");
$scope.BusinessTypeAction = "";
$scope.divBusinessType = false;
}, function () {
alert('Error in Updating Record');
});
} else {
**// Save Section**
var getExistBusinessCode = businessTypeService.checkBusinessTypeCode(businessType.Code);
getExistBusinessCode.then(function (businessTypeCode) {
debugger;
if (businessTypeCode == true) {
alert('Business Type Code Already Exist');
} else {
debugger;
var getBusinessTypeData = businessTypeService.addBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Added Successful");
$scope.divBusinessType = false;
}, function () {
alert("Error Occured In Saving Data");
});
}
},function() {
alert('Error Occured While Checking Records');
});
}
}
In the above code Save Section I am trying to check if a value is exists in a database so I'm passing a string value to: checkBusinessTypeCode(businessType.Code) Service.When I Debug and See Value its Seems Normal.
Here's My Service:
//Check Business Code
this.checkBusinessTypeCode = function (businessTypeCode) {
debugger;
var response = $http({
method: "post",
url: "/BusinessType/CheckBusinessTypeDetailByCode",
params: {
businessTypeCode: JSON.stringify(businessTypeCode)
}
});
return response;
}
But when Passing To Controller string value I get some unexpected behavior.
two \\ always appear automatically
example
"\"stringvalue\""
I'm Still Having Above Problem
but as a quick solution i did code as follows
public bool _CheckBusinessTypeDetailByCode(string businessTypeCode)
{
string bisCode = businessTypeCode.Replace("\"", "");
bool isExist;
isExist = _IBusinessTypeRepository.IsExist(x => x.IsActive && !x.IsDelete && x.Code == bisCode);
return isExist;
}
I don't know is it bad practice or not , any way it is solved my problem.
Before did this modification
string businessTypeCode always gives value as
"\"somevalue\""
Background:
I have a Parse database of images. Simply, my code does this:
A user, through a Parse Cloud call requests an image ("getNewPicture"). Nested within I check if he has seen any pictures before (alongside other requirements) and if so deliver one specific picture (getSpecifiedPicture). If he has not, then I deliver a new picture (getNewPicture).
Issue:
Calling "getNewPicture" through Parse Cloud Code function I get an error code 141. What's strange is that it works through Android but not iOS.
My code:
Parse.Cloud.define("getNewPicture", function(request, response) {
var SeenPictures = Parse.Object.extend("SeenPictures");
var query = new Parse.Query(SeenPictures);
var username = request.params.username;
var notWantedPics = [];
query.ascending("createdAt");
query.equalTo("username", username);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
if (results[i].get("likes") == 1 || results[i].get("dislikes") == 1) {
notWantedPics.push(results[i].get("pictureId"));
results.splice(i, 1);
i--;
}
}
if (results != 0) {
getSpecifiedPicture(results[0].get("pictureId"), {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
} else {
getNewPicture(username, notWantedPics, {
success: function(returnValue) {
response.success(returnValue);
},
error: function(error) {
response.error(error);
}
});
}
},
error: function() {
response.error(error);
}
});
});
function getSpecifiedPicture(specifiedPic, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.get(specifiedPic, {
success: function(picture) {
callback.success(picture);
},
error: function(error) {
callback.error(error);
}
});
}
function getNewPicture(username, notWantedPics, callback) {
var Pictures = Parse.Object.extend("Pictures");
var pictures = new Parse.Query(Pictures);
pictures.notEqualTo("photographerUserName", username);
pictures.notContainedIn("objectId", notWantedPics);
pictures.ascending("createdAt");
pictures.find({
success: function(results) {
if (results.length > 0) {
var object = results[0];
//Some other fancy stuff
object.save();
callback.success(object);
}
},
error: function(error) {
callback.error(error);
}
});
}
Why am I getting code 141? Any help is appreciated.
Thanks.
Your callbacks are a mess. I rewrote it to follow more of a promise chain style. Much easier to follow. Also, underscore.js is your friend. Hopefully I got your idea right.
var _ = require('underscore'); // Javascript Library
Parse.Cloud.define("getNewPicture", function(request, response) {
var username = request.params.username;
var notWantedPics = [];
if (!username) {
return response.error('No username.');
}
var query1 = new Parse.Query("SeenPictures");
query1.ascending("createdAt");
query1.equalTo("username", username);
var SeenPictures = query1.find();
return Parse.Promise.when([SeenPictures]).then(function (SeenPictures) {
SeenPictures = _.filter(SeenPictures, function (SeenPicture) {
if (SeenPicture.get("likes") == 1 || SeenPicture.get("dislikes") == 1) {
notWantedPics.push(SeenPicture.get("pictureId"));
return false;
}
else {
return true;
}
});
// notWantedPics?
if (SeenPictures > 0) {
var query2 = new Parse.Query("Pictures");
var Pictures = [query2.get(SeenPictures[0].get('pictureId'))];
}
else {
var query2 = new Parse.Query("Pictures");
query2.notEqualTo("photographerUserName", username);
query2.notContainedIn("objectId", notWantedPics);
query2.ascending("createdAt");
var Pictures = query2.find();
}
return Parse.Promise.when([Pictures]);
}).then(function (Pictures) {
if (Pictures > 0) {
// Success
return response.success(Pictures[0]);
} else {
return Parse.Promise.error("No pictures.");
}
}, function (error) {
// Error
return response.error(error);
});
});
I am trying to authenticate my social media accounts through Parse via OAuth and it authenticates fine but i keep getting a Failed with success/error was not called; my code is below, can anyone help?
Parse.Cloud.define("createNewNetwork", function(request, response) {
Parse.Cloud.useMasterKey();
//console.log(request.user.id);
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.equalTo("userId", request.params.userId);
query.equalTo("owner", request.user);
query.first({useMasterKey:true}).then(function(network) {
var newNetwork;
if (!network) {
newNetwork = new Network();
var custom_acl = new Parse.ACL();
custom_acl.setWriteAccess(request.user, true);
custom_acl.setPublicReadAccess(true);
newNetwork.setACL(custom_acl);
newNetwork.set("userId", request.params.userId);
newNetwork.set("followingCount", request.params.followingCount);
newNetwork.set("owner", request.user);
newNetwork.set("userData", request.params.userData);
newNetwork.set("networkName", request.params.networkName);
newNetwork.set("screenName", request.params.screenName);
} else {
newNetwork = network;
}
newNetwork.set("tokenExpired", false);
//console.log(request.params.oAuthData["access_token"]);
if (request.params.networkName == "facebook-page") {
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.1/oauth/access_token?grant_type=fb_exchange_token&client_id=**************&client_secret=***************&fb_exchange_token='+request.params.oAuthData["access_token"],
success: function(httpResponse2) {
//console.log(httpResponse2);
if (httpResponse2.status == 200) {
var data = {};
data["access_token"] = httpResponse2.text.substring(13);
newNetwork.save({oAuthData : data}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
} else {
response.error("invalid token");
}
},
error: function(httpResponse2) {
console.log(httpResponse2);
response.error('Request failed with response code ' + httpResponse2.status);
}
});
} else {
newNetwork.save({oAuthData : request.params.oAuthData}, {
success: function(savedNetwork) {
response.success(savedNetwork);
},
error: function(error) {
response.error(error);
}
});
}
});
} else {
response.error("not in role");
}
});
});
Parse.Cloud.define("fetchNetworks", function(request, response) {
var attributesToHide = ["oAuthData"];
Parse.Cloud.useMasterKey();
userHasRole(request.user.id, 'AllUsers').then(function(hasRole){
if (hasRole){
var Network = Parse.Object.extend("Network");
var query = new Parse.Query(Network);
query.descending("followingCount");
var user = new Parse.User();
user.id = request.params.userToFetch;
user.fetch({}).then(function(user) {
query.equalTo("owner", user);
query.find().then(function(networks) {
networks.forEach(function(network) {
attributesToHide.forEach(function(attr) {
delete network.attributes[attr];
});
});
return response.success(networks);
});
});
} else{
response.success({super: false});
}
});
});
Line No - 101 - Removal of return should work.
I am making a private chatting application using private_pub, my question is how to unsubscribe from a channel using private_pub?
thanks for your help
if you are using pjax or ajax a lot in your site and the page you are loading with ajax you have private_pub subscribe method there you will find that It's subscribing many times
after searching a lot about that I found these fork from privat_pub javascript file which solved these problem
var PrivatePub = (function (doc) {
var self = {
connecting: false,
fayeClient: null,
fayeCallbacks: [],
subscriptions: {},
subscriptionCallbacks: {},
faye: function(callback) {
if (self.fayeClient) {
callback(self.fayeClient);
} else {
self.fayeCallbacks.push(callback);
if (self.subscriptions.server && !self.connecting) {
self.connecting = true;
if (typeof Faye === 'undefined') {
var script = doc.createElement("script");
script.type = "text/javascript";
script.src = self.subscriptions.server + ".js";
script.onload = self.connectToFaye;
doc.documentElement.appendChild(script);
} else {
self.connectToFaye();
}
}
}
},
connectToFaye: function() {
self.fayeClient = new Faye.Client(self.subscriptions.server);
self.fayeClient.addExtension(self.fayeExtension);
for (var i=0; i < self.fayeCallbacks.length; i++) {
self.fayeCallbacks[i](self.fayeClient);
};
},
fayeExtension: {
outgoing: function(message, callback) {
if (message.channel == "/meta/subscribe") {
// Attach the signature and timestamp to subscription messages
var subscription = self.subscriptions[message.subscription];
if (!message.ext) message.ext = {};
message.ext.private_pub_signature = subscription.signature;
message.ext.private_pub_timestamp = subscription.timestamp;
}
callback(message);
}
},
sign: function(options) {
if (!self.subscriptions.server) {
self.subscriptions.server = options.server;
}
if (!self.subscriptions[options.channel]) {
self.subscriptions[options.channel] = options;
self.faye(function(faye) {
faye.subscribe(options.channel, self.handleResponse);
});
}
},
handleResponse: function(message) {
if (message.eval) {
eval(message.eval);
}
if (callback = self.subscriptionCallbacks[message.channel]) {
callback(message.data, message.channel);
}
},
subscribe: function(channel, callback) {
self.subscriptionCallbacks[channel] = callback;
}
};
return self;
}(document));
try it.