How to point to source url in couchdb replicate? - couchdb

I have a local PouchDB that must sync with a remote CouchDB. I'm trying (so far without success) to replicate the local one (on localhost:8081) to the remote one (on localhost:5984) through a POST call to /_replicate.
No matter what I enter in the "source" field of my request, it appends "http:127.0.0.1:5984/" to the source url (or name) and, obviously, I get an error saying it can't find the source db. Of course.
My question (which is, by the way, my very first question on StackOverFlow so please be indulgent) is then: how can I point to the correct db?
Thanks!
let url = `http://127.0.0.1:5984/_replicate`;
let data = {
// This is where I struggle
"source" : "http://127.0.0.1:8081/_pouch_local_db",
"target" : `http://127.0.0.1:5984/mydb-${username}`
}
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
}).then(response => {
console.log('Success syncing: ', response);
}).catch(error => console.error('Error while syncing: ', error));

Your code suggests you are asking CouchDb to replicate with a local PouchDb database? That will not work as PouchDb is intended to be a client-side database system. In normal use, PouchDb is not a server (I know there is a PouchDb server available but I do not think that is of help here).
You should use the PouchDb API (include the PouchDB library in your Javascript code) and tell your local PouchDb database to replicate with the CouchDb server on port 5984.
I would expect your code to look like this:
var dblocal = new PouchDB('local_db');
var dbremote = new PouchDB('http://127.0.0.1:5984/myremotedb');
dblocal.replicate.to(dbremote, function (err, result) {
if (err) { return console.log(err); }
// handle 'completed' result
});
I am assuming you have not password-protected your test CouchDb database. If you have, you will need to include a username and password in the "auth" options for the remote database when using new PouchDB.
There are some examples and information on the PouchDB site.

Related

Node.js - Why does my HTTP GET Request return a 404 when I know the data is there # the URL I am using

I'm still new enough with Node that HTTP requests trip me up. I have checked all the answers to similar questions but none seem to address my issue.
I have been dealt a hand in the Wild of having to go after JSON files in an API. I then parse those JSON files to separate them out into rows that populate a SQL database. The API has one JSON file with an ID of 'keys.json' that looks like this:
{
"keys":["5sM5YLnnNMN_1540338527220.json","5sM5YLnnNMN_1540389571029.json","6tN6ZMooONO_1540389269289.json"]
}
Each array element in the keys property holds the value of one of the JSON data files in the API.
I am having problems getting either type of file returned to me, but I figure if I can learn what is wrong with the way I am trying to get 'keys.json', I can leverage that knowledge to get the individual JSON data files represented in the keys array.
I am using the npm modules 'request' and 'request-promise-native' as follows:
const request = require('request');
const rp = require('request-promise-native');
My URL is constructed with the following elements, as follows (I have used the ... to keep my client anonymous, but other than that it is a direct copy:
let baseURL = 'http://localhost:3000/Users/doug5solas/sandbox/.../server/.quizzes/'; // this is the development value only
let keysID = 'keys.json';
Clearly the localhost aspect will have to go away when we deploy but I am just testing now.
Here is my HTTP call:
let options = {
method: 'GET',
uri: baseURL + keysID,
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (res) {
jsonKeysList = res.keys;
console.log('Fetched', jsonKeysList);
})
.catch(function (err) {
// API call failed
let errMessage = err.options.uri + ' ' + err.statusCode + ' Not Found';
console.log(errMessage);
return errMessage;
});
Here is my console output:
http://localhost:3000/Users/doug5solas/sandbox/.../server/.quizzes/keys.json 404 Not Found
It is clear to me that the .catch() clause is being taken and not the .then() clause. But I do not know why that is because the data is there at that spot. I know it is because I placed it there manually.
Thanks to #Kevin B for the tip regarding serving of static files. I revamped the logic using express.static and served the file using that capability and everything worked as expected.

How to access manually created index in pouchdb find

I am pretty new to pouchDB and couchDB. I've trying to use pouchdb find but having some problems.
I have created a view "test" and source -
function(doc) {
emit(doc.name, doc.occupation);
}
and when i run this -
localDB.query('test/test').then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});
Everything works as expected.
But when i try pouchdb find -
localDB.find({
selector: {name: 'kittens'}
}).then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err);
});
I got following error -
Error: couldn't find a usable index. try creating an index on: name.
If i create index by
localDB.createIndex({
index: {
fields: ['name']
}
});
only then pouchdb find code works. But when i manually created an index (shown in image above) then it doesn't.
Any help is appreciated. Thanks in advance.
pouchdb-find uses the new "Mango" query language, which is different from map/reduce. Mango is only supported in CouchDB 2.0+ and PouchDB Server, not CouchDB 1.x.
So at this time you will need to either use CouchDB 2.0 or PouchDB Server with pouchdb-find if you want it to work on both the client and the server, or you will need to use regular map/reduce instead and avoid pouchdb-find.

Error: It is not secure to become a user on a node.js server environment

I've used the method
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
This method will call back to Parse to validate the session token and fetch the associated user, then set the current user on the client like is explained in this website
http://blog.parse.com/announcements/bring-your-own-login/
This method was working perfectly but I recently update the last version of npm parse 1.5.0 and now I got the following error:
Error: It is not secure to become a user on a node.js server environment.
at Function.Parse.User.Parse.Object.extend.become (/home/...
Anybody has a solution for this problem?
Thanks in advance
Ran into the same issue. While bypassing the Javascript SDK may work, it appears that you can use Parse.User.enableUnsafeCurrentUser() help bypass this error within the SDK.
In the Parse 1.5.0 Javascript SDK section of their change log they provided the following update:
Removed the concept of the current user when running in node.js Current users can be enabled in node with Parse.User.enableUnsafeCurrentUser() Many requests now support passing an explicit session token as an option
There may be some unintended security issues with this method. In reading through the source code this will also allow you to also use Parse.User.current and other like features as well. Using .become is probably still the safest option while managing your own session information.
I've been having a lot of issues with Parse.User.become(), both between the error you mentioned, and it returning a 101 invalid user session. My workaround was to bypass the Javascript SDK and make a Parse REST API request.
var request = require("request"),
q = require("q"),
deferred = q.defer(),
options = {
url: "https://api.parse.com/1/users/me",
method: "GET",
json: true,
headers: {
"X-Parse-Session-Token": token,
"X-Parse-Application-Id": "PARSE_APPLICATION_ID",
"X-Parse-REST-API-Key": "PARSE_RESET_API_KEY"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
return deferred.resolve(user);
} else {
return deferred.reject(error);
}
});
return deferred.promise;

Google+ insert moment with nodejs client

Has anyone been able to get the google-api-nodejs-client to successfully insert a moment?
Whatever I try, I get a generic 400 "Invalid value" error but am unable to narrow down the invalid value because the API Explorer doesn't work either.
Would it be because of the missing data-requestvisibleactions parameter? I'm using passport.js's require('passport-google-oauth').OAuth2Strategy for handling oauth access, and that part is working fine, but I have no idea how to incorporate requestvisibleactions into the oauth request flow since this is definitely not originating from a clientside form.
Here's a snippet of what I'm trying to do (using the latest version of googleapis, v1.0.2):
var google = require('googleapis')
var auth = new google.auth.OAuth2()
auth.setCredentials({
'access_token': user.token
})
google.plus('v1').moments.insert({
collection: 'vault',
userId: 'me',
debug: true,
resource: {
type: "http://schemas.google.com/AddActivity",
target: {
type: "http://schema.org/CreativeWork",
url: "...omitted...",
image: "...omitted...",
description: "test",
name: "test"
}
},
auth: auth
}, function (err, response) {
if (err) {
console.error(err)
res.send(err.code, err)
} else {
console.log(response)
res.send(200)
}
})
ref 1 (out-of-date w.r.t. an older version of googleapis)
ref 2 (client-side, where the use of data-requestvisibleactions is more obvious)
As you speculated, you need the request_visible_actions parameter as part of the URL calling the oauth endpoint.
It looks like the current version of passport-google-oauth doesn't support this parameter. Judging by several of the open issues and pull requests, it isn't clear that the author will respond to requests to add it either. You have two possible options:
Switch to using the OAuth support that is included in google-api-nodejs-client
Patch the passport-google-oauth code. (And possibly submit a pull request in the hopes it will be useful to someone else.)
I don't use passport.js or the passport module in question, so I can't test this, but based on the github repository, I think you can insert the following in lib/passport-google-oauth/oauth2.js after line 136 and before the return statement:
if (options.requestVisibleActions) {
// Space separated list of allowed app actions
// as documented at:
// https://developers.google.com/+/web/app-activities/#writing_an_app_activity_using_the_google_apis_client_libraries
// https://developers.google.com/+/api/moment-types/
params['request_visible_actions'] = options.requestVisibleActions;
}

How to replicate from CouchDB to PouchDB?

I've set up a local CouchDB database and I'd like to replicate it to a PouchDB database, using JavaScript in a web page running on localhost.
With the code below I get this error:
Origin http://localhost is not allowed by Access-Control-Allow-Origin.
With http:// removed from REMOTE, I don't get an error, but no docs are shown as replicated.
Looking at IndexedDB databases from Chrome DevTools, I can see the database has been created (but doesn't appear to have documents).
Running in Chrome 29.0.1535.2 canary.
Can I do this locally, or do I need to set up a remote CouchDB database and enable CORS (as per the CouchDB docs)?
var REMOTE = 'http://127.0.0.1:5984/foo';
var LOCAL = 'idb://foo';
Pouch(LOCAL, function(error, pouchdb){
if (error) {
console.log("Error: ", error);
} else {
var db = pouchdb;
Pouch.replicate(REMOTE, LOCAL, function (error, changes) {
if (error) {
console.log('Error: ', error);
}
else {
console.log('Changes: ', changes);
db.allDocs({include_docs: true}, function(error, docs) {
console.log('Rows: ', docs.rows);
});
}});
}
});
You can do it locally, but CORS has to be enabled.
When you remove "http://" from the remote URL, Pouch is going to replicate your DB into a new IndexedDB-backed Pouchdb named "localhost" (or actually "_pouch_localhost" or something like that - it adds a prefix).
Unless you're serving up this page from CouchDB itself (on the same host & port), you will need to enable CORS to get replication to CouchDB working.

Resources