I'm thinking about making my own JavaScript client library, and I like the way Firebase formats requests. I'm trying to understand whats going on. From looking at the web guide here I found the below code:
var ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog");
var usersRef = ref.child("users");
usersRef.set({
alanisawesome: {
date_of_birth: "June 23, 1912",
full_name: "Alan Turing"
},
gracehop: {
date_of_birth: "December 9, 1906",
full_name: "Grace Hopper"
}
});
I can see that ref is equal to a function called Firebase, and usersRef is equal to ref.child.
I'm imagining something like this:
Firebase = function(url) {
this.child = function(path) {
console.log(url);
console.log(path);
};
};
Here I can see that usersRef.set is being called but I can't figure out how or where this would go? Is set a function or an object? I notice firebase has set(), update(), push() and transaction(), making me think these are functions.
"TypeError: Cannot read property 'set' of undefined
Maybe I'm on the wrong path totally, I'm just not familiar with this pattern.
If you check the Firebase API, you will see that child() returns a new Firebase reference to the child location. So something like this:
var Firebase = function(url) {
console.log(url);
this.child = function(path) {
return new Firebase(url+'/'+path);
};
this.set = function(object) {
console.log(object);
};
};
I've updated you jsbin: https://jsbin.com/nucume/2/edit?js,console
Related
I am attempting to send data entered into various fields of an HTML form on a webpage as a JSON string to AWS Lambda so that Lambda can enter that into a DynamoDB table. As this is for a class project, I've chosen to forego using a Gateway API, I just want to raw call the Lambda function from inside the webpage javascript and pass the JSON in as a parameter to the Lambda function. I have the webpage successfully calling the Lambda function, which I have hard coded to enter a predefined entry into the Dynamo table. I also have the web js making a JSON string from the form. My goal is to send the JSON string as a parameter to the Lambda function when I invoke it, but I'm not sure how I would go about that, as this is my first time working with AWS. I know I have to do something with the payload parameter, but I can't find a clear example as to what. I've made sure I have the proper credentials and SDK imports in the HTML. Below is my code:
Webpage JS:
var lambda = new AWS.Lambda();
function makeJSON(){
var userID = "";
var name = document.forms["characterForm"]["characterName"].value;
//alert(name);
//alert(typeof name);
var race = document.forms["characterForm"]["race"].value;
var playerClass = document.forms["characterForm"]["class"].value;
var strength = document.forms["characterForm"]["strength"].value;
var dexterity = document.forms["characterForm"]["dexterity"].value;
var constitution = document.forms["characterForm"]["constitution"].value;
var intelligence = document.forms["characterForm"]["intelligence"].value;
var wisdom = document.forms["characterForm"]["wisdom"].value;
var charisma = document.forms["characterForm"]["charisma"].value;
//alert(name + race + playerClass + strength, dexterity, constitution, intelligence, wisdom, charisma);
characterSheetObj = {userID: userID, name: name, race: race, class: playerClass, strength: strength, dexterity: dexterity, constitution: constitution, intelligence: intelligence, wisdom: wisdom, charisma: charisma}
characterSheetJSON = JSON.stringify(characterSheetObj);
var myParams = {
FunctionName : 'addCharacterSheet',
InvocationType : 'RequestResponse',
LogType : 'None',
//Payload : {"userID": userID, "name": name, "race": race, "class": playerClass, "strength": strength, "dexterity": dexterity, "constitution": constitution, "intelligence": intelligence, "wisdom": wisdom, "charisma" : charisma}
}
lambda.invoke(myParams, function(err, data){
//if it errors, prompts an error message
if (err) {
alert("Error");
prompt(err);
}
//otherwise puts up a message that it didnt error. the lambda function presently doesnt do anything
//in the future the lambda function should produce a json file for the JavaScript here to do something with
else {
alert("Invoked Lambda function without erroring!");
}
});
}
Node Lambda Function:
const AWS = require('aws-sdk');
const db = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = async (event) => {
// exports.handler = function(e, ctx, callback) {
let scanningParameters = {
TableName : 'characterTable',
Limit:100
};
db.scan(scanningParameters, function(err, data){
if(err){
callback(err,null);
}else{
callback(null,data);
}
});
const params = {
TableName : 'characterTable',
Item: {
name : 'Alan'
}
};
const userID = '12345';
params.Item.userID = userID;
return await db.put(params).promise();
};
//}
I think it has to do with events.body in the Node.js code, but again, I'm not very clear on it, and I can't suss very much out of Amazon's documentation. Any suggestions, tips, or resources to look at would be greatly appreciated!
I don't know if I understand your question correctly but your parameters passed to AWS Lambda is available at event.arguments
Just pass the payload as a JSON string:
var payload_obj = { name: "John", age: 30, city: "New York" };
var payload_json = JSON.stringify(payload_obj);
var myParams = {
FunctionName: 'addCharacterSheet',
InvocationType: 'RequestResponse',
LogType: 'None',
Payload: payload_json
}
lambda.invoke(myParams, function(err, data){
...
});
I have a very basic feathers service which stores data in mongoose using the feathers-mongoose package. The issue is with the get functionality. My model is as follows:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
When the a user runs a GET command :
curl http://localhost:3030/messages/test
I have the following requirements
This essentially tries to convert test to ObjectID. What i would
like it to do is to run a query against the message attribute
{message : "test"} , i am not sure how i can achieve this. There is
not enough documentation for to understand to write or change this
in the hooks. Can some one please help
I want to return a custom error code (http) when a row is not found or does not match some of my criterias. How can i achive this?
Thanks
In a Feathers before hook you can set context.result in which case the original database call will be skipped. So the flow is
In a before get hook, try to find the message by name
If it exists set context.result to what was found
Otherwise do nothing which will return the original get by id
This is how it looks:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
How to create custom errors and set the error code is documented in the Errors API.
I pretty much copied the example and adjusted the database query. I dont understand why the driver is not recognized?
Version:
Node: v11.13.0
neo4j-driver: "^1.7.5"
I get the Error:
var driver = neo4j.v1.driver(
^
TypeError: Cannot read property 'driver' of undefined
My Code:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.v1.driver(
'bolt://localhost:7687',
neo4j.auth.basic('neo4j', 'Neo4j')
)
var session = driver.session()
session
.run('MATCH (n:Person) return n', {
//nameParam: 'Alice'
})
.subscribe({
onNext: function(record) {
console.log(record.get('n'))
},
onCompleted: function() {
session.close()
},
onError: function(error) {
console.log(error)
}
})
You probably meant to do this:
var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver(
...
Or, if for some reason you want to be able to explicitly specify the library version every time you use it, do this:
var neo4j = require('neo4j-driver');
var driver = neo4j.v1.driver(
...
their docs seem screwed up, I had the exact same problem.
remove the v1 and it works. not sure if this defaults to a different version of the driver or something...
let config = require("./config")[env]
const uri = 'bolt://localhost:7687'
const neo4j = require('neo4j-driver');
const driver = neo4j.driver(uri, neo4j.auth.basic(config.username, config.password));
FWIW the way they define a config file is also broken. the node onboarding is pretty much a turn-off.
I am currently using PouchDB as my DB and I am using Cloudant for the remote service. I am currently trying to create document, however, when I invoke the function, I have errors.
May I know where did I do wrong? Could it be the URL wrong or my syntax is wrong?
Uncaught Reference Error: PouchDB is not a constructor
This is my javascript code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
window.PouchDB = db;
var doc = {
"_id": "Can123",
"name": "You123",
"occupation": "See1",
"age": 3,
"hobbies": [
"Watch 9pm show",
"chasing laser pointers",
"lookin' hella cute"
]
};
db.put(doc);
PouchDB.sync(db, remoteDB);
}
HTML code
<button onclick="pouchdb()">pouchdb</button>
Update
I changed my insert code for this set of code
function pouchdb() {
var db = new PouchDB("todos");
var remoteDB = new PouchDB("http://example.cloudant.com/example");
var todo = {
_id: "mittens1233",
title: "hello",
occupation: "kitten123"
};
db.put(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
The result i got back is Successfully posted a todo!, however, my cloudant dashboard still shows 0 doc. May I know why?
Remove that line
window.PouchDB = db;
I think that's the problem. Once you click the button, the global PouchDB turns the variable db, what makes it not be a constructor anymore.
If the error still continues, #gcampbell comment should be right?
I'm using Backbone.js to route profile views so I can view data belonging to /user, and that part works fine. I'm able to generate an _id based on the username and pass it into the server publish function, which logs it. However, when I log the results back to the client in the subscribe function, my result looks like this:
Object {stop: function, ready: function}
//Client Side
Template.userquery.userproject = function() {
var query = Session.get('userquery');
var user = Meteor.users.findOne({username: query});
if (user) {
console.log(user._id); //(works)
campaigns = Meteor.subscribe('userquery', user._id, function() {
console.log('ready'); //(works)
});
console.log(campaigns); //(returns Object {stop: function, ready: function})
return campaigns;
}
}
//Server Side
Meteor.publish('userquery', function(userid) {
console.log('break');
console.log(userid); //(I get userid in Terminal)
var campaigns = Campaigns.find({owner: userid}, {fields: {owner: 1, name: 1}});
if (campaigns) {
console.log(campaigns);
return campaigns;
}
});
Am I missing something in this function? I have autopublish turned off because it was generating my search twice.
Meteor.subscribe, according to the docs, "Returns a handle that provides stop() and ready() methods." So the behaviour you're seeing is intended.