Skip to content

Instantly share code, notes, and snippets.

@aeharding
Created November 26, 2016 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeharding/abed2faac14073d9733c665c62ce87aa to your computer and use it in GitHub Desktop.
Save aeharding/abed2faac14073d9733c665c62ce87aa to your computer and use it in GitHub Desktop.
Trying to replicate pouchdb/pouchdb#5943
<!DOCTYPE html>
<html>
<head>
<script src="//cdn.jsdelivr.net/pouchdb/6.0.7/pouchdb.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
</head>
<body>
<button onclick="seed()">Seed the database with 10000 docs</button><br>
<button onclick="recreate()">Destroy and recreate database</button><br>
<button onclick="verifyDocs()">Verify 10000 docs exist</button><br>
<button onclick="startReplication()">Start sync with remote DB</button>
<script>
create(); // initialize
var db, sync;
function create() {
db = new PouchDB('my_database', {
size: 50
});
}
function seed() {
return db.bulkDocs(_.range(10000).map(number => {
return {
_id: `doc_${number}`
};
}))
.then(res => {
var error = _.find(res, d => d.error);
if (error) {
console.log('⚠️ Seed unsuccessful');
} else {
console.log('✅ Seed successful');
}
})
.catch(e => {
console.log('⚠️ Seed NOT successful!');
});
}
function recreate() {
if (sync) {
sync.cancel();
}
return db.destroy()
.then(create)
.then(() => {
console.log('✅ Recreation successful');
})
.catch(e => {
console.log('⚠️ Recreation NOT successful!');
});
}
function verifyDocs() {
return db.allDocs({
startkey: `doc_`,
endkey: `doc_\uffff`,
include_docs: true
})
.then(({ rows }) => {
if (rows.length !== 10000) {
console.log(`⚠️ Document row count not 10000! Got ${rows.length}.`);
} else {
console.log(`✅ Successfully got all rows.`);
}
})
.catch(e => {
console.log('⚠️ Something went wrong getting docs!');
});
}
function startReplication() {
sync = db.sync('http://localhost/db/my_database', {
live: true,
retry: true,
batch_size: 500
})
.on('change', function (info) {
console.log('Syncing...');
})
.on('paused', function () {
// user went offline
console.log('✅ Completed sync');
verifyDocs();
})
.on('active', function () {
console.log('Syncing...');
// replicate resumed (e.g. user went back online)
})
.on('denied', function (info) {
console.log('⚠️ Denied!');
// a document failed to replicate (e.g. due to permissions)
})
.on('complete', function (info) {
console.log('⚠️ Error! Complete!');
// handle complete
})
.on('error', function (err) {
console.log('⚠️ Error!');
// handle error
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment