How to reload Loki database and collection from persistence - lokijs

[UPDATE] I laterly found out some example which is like:
this.db = new Loki("viewsaving", {
autosave: true,
autosaveInterval: 5000,
autoload: true,
autoloadCallback: function(){
db_ready = true;
if(db.getCollection("namedviews") == null ){
this.namedviews = db.addCollection("namedviews");
}
if(db.getCollection("timedviews") == null ){
this.timedviews = db.addCollection("timedviews");
}
}
});
It basically works on my side. so I just use it, not sure if this is correct or not, please advise.
All:
I am pretty new to Lokijs, I wonder how can I reload the database and collection which has been persisted?
Say that I build a database and collection, then I persist it( like click a button to trigger persistence process):
var db = new Loki("mydb");
var users = db.addCollection('users');
// we bind this to a button click event
function saveUser(){
users.insert({
name: 'joe'
});
users.insert({
name: 'john'
});
users.insert({
name: 'jack'
});
db.saveDatabase();
}
Then when I refresh this page, how can I load "mydb" and "users" from persistence rather than create new one( cos it will go thru var db = new Loki("mydb"); again ), is there API to check if a database exists?

const db = new loki('example.json', {
env: 'BROWSER',
autosave: true,
autosaveInterval: 500,
autoload: true })
You need to assign the 'env' property to 'BROWSER'

As far as I can tell its not possible to persist to a clientside DB as its difficult and generally insecure for the browser to have access to the local file system. Lokijs supports persistence within the browser's local storage. Loki uses an adapter to implement persistence to the browsers local storage, this adapter defaults to 'localStorage adapter.
var db = new Loki("test.db", {
autoload: true,
autoloadCallback : databaseInitialize,
autosave: true,
autosaveInterval: 4000,
//adapter: 'default already set'
});
For more details see https://rawgit.com/techfort/LokiJS/master/jsdoc/tutorial-Persistence%20Adapters.html

Related

how to connect postgresql with graphql [duplicate]

GraphQL has mutations, Postgres has INSERT; GraphQL has queries, Postgres has SELECT's; etc., etc.. I haven't found an example showing how you could use both in a project, for example passing all the queries from front end (React, Relay) in GraphQL, but to a actually store the data in Postgres.
Does anyone know what Facebook is using as DB and how it's connected with GraphQL?
Is the only option of storing data in Postgres right now to build custom "adapters" that take the GraphQL query and convert it into SQL?
GraphQL is database agnostic, so you can use whatever you normally use to interact with the database, and use the query or mutation's resolve method to call a function you've defined that will get/add something to the database.
Without Relay
Here is an example of a mutation using the promise-based Knex SQL query builder, first without Relay to get a feel for the concept. I'm going to assume that you have created a userType in your GraphQL schema that has three fields: id, username, and created: all required, and that you have a getUser function already defined which queries the database and returns a user object. In the database I also have a password column, but since I don't want that queried I leave it out of my userType.
// db.js
// take a user object and use knex to add it to the database, then return the newly
// created user from the db.
const addUser = (user) => (
knex('users')
.returning('id') // returns [id]
.insert({
username: user.username,
password: yourPasswordHashFunction(user.password),
created: Math.floor(Date.now() / 1000), // Unix time in seconds
})
.then((id) => (getUser(id[0])))
.catch((error) => (
console.log(error)
))
);
// schema.js
// the resolve function receives the query inputs as args, then you can call
// your addUser function using them
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: {
type: userType,
args: {
username: {
type: new GraphQLNonNull(GraphQLString),
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
resolve: (_, args) => (
addUser({
username: args.username,
password: args.password,
})
),
},
}),
});
Since Postgres creates the id for me and I calculate the created timestamp, I don't need them in my mutation query.
The Relay Way
Using the helpers in graphql-relay and sticking pretty close to the Relay Starter Kit helped me, because it was a lot to take in all at once. Relay requires you to set up your schema in a specific way so that it can work properly, but the idea is the same: use your functions to fetch from or add to the database in the resolve methods.
One important caveat is that the Relay way expects that the object returned from getUser is an instance of a class User, so you'll have to modify getUser to accommodate that.
The final example using Relay (fromGlobalId, globalIdField, mutationWithClientMutationId, and nodeDefinitions are all from graphql-relay):
/**
* We get the node interface and field from the Relay library.
*
* The first method defines the way we resolve an ID to its object.
* The second defines the way we resolve an object to its GraphQL type.
*
* All your types will implement this nodeInterface
*/
const { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
const { type, id } = fromGlobalId(globalId);
if (type === 'User') {
return getUser(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}
return null;
}
);
// a globalId is just a base64 encoding of the database id and the type
const userType = new GraphQLObjectType({
name: 'User',
description: 'A user.',
fields: () => ({
id: globalIdField('User'),
username: {
type: new GraphQLNonNull(GraphQLString),
description: 'The username the user has selected.',
},
created: {
type: GraphQLInt,
description: 'The Unix timestamp in seconds of when the user was created.',
},
}),
interfaces: [nodeInterface],
});
// The "payload" is the data that will be returned from the mutation
const userMutation = mutationWithClientMutationId({
name: 'AddUser',
inputFields: {
username: {
type: GraphQLString,
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
outputFields: {
user: {
type: userType,
resolve: (payload) => getUser(payload.userId),
},
},
mutateAndGetPayload: ({ username, password }) =>
addUser(
{ username, password }
).then((user) => ({ userId: user.id })), // passed to resolve in outputFields
});
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: userMutation,
}),
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
user: {
type: userType,
args: {
id: {
description: 'ID number of the user.',
type: new GraphQLNonNull(GraphQLID),
},
},
resolve: (root, args) => getUser(args.id),
},
}),
});
We address this problem in Join Monster, a library we recently open-sourced to automatically translate GraphQL queries to SQL based on your schema definitions.
This GraphQL Starter Kit can be used for experimenting with GraphQL.js and PostgreSQL:
https://github.com/kriasoft/graphql-starter-kit - Node.js, GraphQL.js, PostgreSQL, Babel, Flow
(disclaimer: I'm the author)
Have a look at graphql-sequelize for how to work with Postgres.
For mutations (create/update/delete) you can look at the examples in the relay repo for instance.
Postgraphile https://www.graphile.org/postgraphile/ is Open Source
Rapidly build highly customisable, lightning-fast GraphQL APIs
PostGraphile is an open-source tool to help you rapidly design and
serve a high-performance, secure, client-facing GraphQL API backed
primarily by your PostgreSQL database. Delight your customers with
incredible performance whilst maintaining full control over your data
and your database. Use our powerful plugin system to customise every
facet of your GraphQL API to your liking.
You can use an ORM like sequelize if you're using Javascript or Typeorm if you're using Typescript
Probably FB using mongodb or nosql in backend. I've recently read a blog entry which explain how to connect to mongodb. Basically, you need to build a graph model to match the data you already have in your DB. Then write resolve, reject function to tell GQL how to behave when posting a query request.
See https://www.compose.io/articles/using-graphql-with-mongodb/
Have a look at SequelizeJS which is a promise based ORM that can work with a number of dialects; PostgreSQL, MySQL, SQLite and MSSQL
The below code is pulled right from its example
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite',
// http://docs.sequelizejs.com/manual/tutorial/querying.html#operators
operatorsAliases: false
});
const User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
sequelize.sync()
.then(() => User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
}))
.then(jane => {
console.log(jane.toJSON());
});

insert data to external mongodb with meteor app

I have an instant of mongodb in the server , ana i connect my meteor app to this DB using that code : lib/connection.js
MONGO_URL = 'mongodb://xxxxxxxx';
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect(MONGO_URL, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to cc', MONGO_URL);
var collection = db.collection('test');
var test1= {'hello':'test1'};
collection.insert(test1);
db.close();
}
});
the connextion to the the external mongo is established and the collection test is created in the server but my app still connected to the the local mongo when i insert my collection: books:
thee code : collections/Books.js
Books= new Mongo.Collection('books');
BooksSchema= new SimpleSchema({
name: {
type: String,
label: "Name"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
categorie:{
type: String,
label: "Categorie"
autoform:{
label: false,
placeholder: "schemaLabel"
}
},
});
Meteor.methods({
deleteBook: function(id) {
Cultures.remove(id);
}
});
Books.attachSchema(BooksSchema);
code client/books.html
<template name="books">
<p>add new books </p>
{{> quickForm collection="Books" id="newBook" type="insert" class="nform" buttonContent='ajouter' buttonClasses='btn bg-orange'}}
</template>
help bleaaaaaz
You should specify the database that is supposed to be used in MONGO_URL environment variable, not in your code. If you work locally start your application like this:
MONGO_URL="mongodb://xxxxxxxx" meteor
UPD
Don't know about Windows. See this SO question.
Looks like you should set env vars in windows like this:
set MONGO_URL=mongodb://localhost:27017/mydbname
ok thnk you Ramil , i create a new system environment variable on windows , MOGO_URL with value equal : mongodb://xxxxxxxx, and it works; the application is connected to the database in the server , and the data is inserted into it .
now my problem is how to get the data from that DB , I user Microsoft azure to stock the db with API DocumentDB

running background job on a specific action in sails js

i am trying to make a service that runs in background when specific event happens. As an example when user verifies email i want my service of deleting possible unverified duplicate emails form database. i tried using kue to save my purpose but i think its more like the services will run once the sails lift fires?
so how to run a service when specific event happens? any help would be much appreciated.
thanks
You can indeed use Kue for this purpose.
Create a config file kue.js for Kue
var kue = require('kue');
var kue_engine = kue.createQueue({
prefix: 'kue',
redis: {
port: '6379',
host: 'localhost'
}
});
process.once('SIGTERM', function (sig) {
kue_engine.shutdown( 5000, function(err) {
console.log( 'Kue shutdown: ', err||'' );
process.exit( 0 );
});
});
module.exports.kue = kue_engine;
Add the job to Kue in relevant controller action.
var kue_engine = sails.config.kue;
kue_engine.create('delete_verified_email', {email: '123#456.com'})
.priority('medium')
.attempts(3)
.save();
Create a worker.js in project root to consume kue jobs.
var kue = require('kue');
require('sails').load({
hooks: {
blueprints: false,
cors: false,
csrf: false,
grunt: false,
http: false,
i18n: false,
logger: false,
policies: false,
pubsub: false,
request: false,
responses: false,
session: false,
sockets: false,
views: false
}
}, function (err, app) {
sails.log.info('Starting kue');
var kue_engine = sails.config.kue;
//register kue.
kue_engine.on('job complete', function (id) {
sails.log.info('Removing completed job: ' + id);
kue.Job.get(id, function (err, job) {
job.remove();
});
});
kue_engine.process('delete_verified_email', 20, function (job, done) {
// you can access the data passed while creating job at job.data
// all the sails models, services are available here
console.log(job.data.email)
done && done();
});
Run the worker.js to consume the kue jobs created by your sails app.
Maybe Sails.js lifecycle hooks could help you. We are using them for instance to update statistics, e.g. persisting number of users per type after a user update call.
Also we are using Node Agenda (Sails.js hook) to create jobs to be executed either one time to a defined time in the future or like a cron job. Maybe you will want to collect the invalid/ expired email address verification entries to be purged and delete them in a hourly batch.

OData Jaydata - odata update request returns error 404 (SAPUI5, node)

I'm building a web application with SAPUI5 which makes available a list of services, that are stored in a MongoDB and available as OData.
I followed this guide jaydata-install-your-own-odata-server-with-nodejs-and-mongodb and these are my model.js:
$data.Class.define("marketplace.Service", $data.Entity, null, {
Id: {type: "id", key: true, computed: true, nullable: false},
Name: {type: "string", nullable: false, maxLength: 50},
}, null);
$data.Class.defineEx("marketplace.Context", [$data.EntityContext, $data.ServiceBase], null, {
Services: {type: $data.EntitySet, elementType: marketplace.Service}
});
exports = marketplace.Context;
and server.js:
var c = require('express');
require('jaydata');
window.DOMParser = require('xmldom').DOMParser;
require('q');
require('./model.js');
var app = c();
app.use(c.query());
app.use(c.bodyParser());
app.use(c.cookieParser());
app.use(c.methodOverride());
app.configure(function() {app.use(app.router);});
app.use(c.session({secret: 'session key'}));
app.use("/marketplace", $data.JayService.OData.Utils.simpleBodyReader());
app.use("/marketplace", $data.JayService.createAdapter(marketplace.Context, function (req, res) {
return new marketplace.Context({
name: "mongoDB",
databaseName: "marketplace",
address: "localhost",
port: 27017
});
}));
app.use("/", c.static(__dirname));
app.use(c.errorHandler());
app.listen(8080);
The client is developed by using SAPUI5 and these are the parts of the code relative to the odata model creation:
oModel = sap.ui.model.odata.ODataModel("http://localhost:8080/marketplace", false); // connection to the odata endpoint
oModel.setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay);
sap.ui.getCore().setModel(oModel);
The various services are correctly showed in a SAPUI5 table and I'm easily able to insert a new service by using the POST OData.request in this way:
OData.request({
requestUri: "http://localhost:8080/marketplace/Services",
method: "POST",
data: newEntry // json object with the new entry
},
function(insertedItem) {
// success notifier
},
function(err) {
// error notifier
}
);
and delete a service by using the SAPUI5 function oModel.remove() in this way (oParams is a json object which contains the alert notification functions):
var serviceId = oTable.getRows()[selectedIndex].getCells()[0].getText();
oModel.remove("/Services('" + serviceId + "')", oParams);
Everything works fine but the update request for a single service. I've tried with the functions provided by SAPUI5 (oModel.update or oModel.submitChanges), by using OData.request ("method: PUT"), by creating an ajax PUT request, I also tried to craft PUT request with Fiddler.
I always get error 404:
Request URL:http://localhost:8080/marketplace/Services('NTMzZDM3M2JlNjY2YjY3ODIwZjlmOTQ0')
Request Method:PUT
Status Code:404 Not Found
Where can be the problem?
I tried with Chrome, IE, and Firefox; same problem...
Thanks
Try to update with MERGE verb and pass the modified fields in JSON format inside the BODY

How to implement ReST services with Sails.js?

I am quite new to Node. I came across Sails.js. I think it is based on WebSocket, which seems to be really good for building real-time applications. I would like to know that whether Sails can be used to implement REST architecture as it uses WebSocket? And if yes, how?
Yes it can. Sails JS allows you to easily build a RESTful API, essentially with no effort to get started. Also, websockets (through socket.io) are integrated by default into the view and api.
To create a fully RESTful app from the ground up, it actually requires no JS. Try:
sails new testapp
cd testapp
sails generate model user
sails generate controller user
cd <main root>
sails lift
The CRUD (Create, Read, Update, Delete) actions are already created for you. No code!
You can create a user in your browser by doing the following:
HTTP POST (using a tool like PostMan) to http://:1337/user/create
{
"firstName": "Bob",
"lastName": "Jones"
}
Next, do a GET to see the new user:
HTTP GET http://:1337/user/
FYI - Sails JS uses a default disk based database to get you going
Done.
sails new testapp
cd testapp
sails generate api apiName
controller
create: function (req, res) {
var payload = {
name:req.body.name,
price:req.body.price,
category:req.body.category,
author:req.body.author,
description:req.body.description
};
Book.create(payload).exec(function(err){
if(err){
res.status(500).json({'error':'something is not right'})
}else{
res.status(200).json({'success':true, 'result':payload, 'message':'Book Created success'})
}
});
},
readone: async function (req, res) {
var id = req.params.id;
var fff = await Book.find(id);
if(fff.length == 0){
res.status(500).json({'error':'No record found from this ID'})
}else{
res.status(200).json({'success':true, 'result':fff, 'message':'Record found'})
}
},
model
attributes: {
id: { type: 'number', autoIncrement: true },
name: { type: 'string', required: true, },
price: { type: 'number', required: true, },
category: { type: 'string', required: true, },
author: { type: 'string' },
description: { type: 'string' },
},
routes
'post /newbook': 'BookController.create',
'get /book/:id': 'BookController.readone',