I'm new to Javascript (and web development in general) and want to display data from a PostgreSQL server on a web page using ag-Grid. I've followed some tutorials and I have successfully pulled data from postgreSQL, and successfully displayed some sample data using ag-Grid. Now I'm trying to combine the two, and I can't figure it out.
I've created a 'database.js' which pulls the data from PostgreSQL - it's modified from this tutorial (LINK):
database.js:
const {Client} = require("pg");
const client = new Client ({
host: "<IPaddress>",
user: "<username>",
port: 5432,
password: "<password>",
database: "postgres"
})
client.connect();
var Query = function(){
client.query( `select * from test1`, (err, res) => {
callback (err, res)
client.end;
})
return {
Query1: Query
}
}();
module.exports = Query;
Then in main.js I have the following which has come from ag-grid tutorials:
main.js:
var QueryResults = require('database');
var columnDefs = [
{headerName: 'Make', field: 'make', sortable: true, filter: true},
{headerName: 'Model', field: 'model', sortable: true, filter: true},
{headerName: 'Price', field: 'price', sortable: true, filter: true}
];
var gridOptions = {
columnDefs: columnDefs,
rowModelType: 'infinite',
datasource: datasource,
};
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
There are a few concerns that I have:
Is my method of referencing my query results in database.js correct.?
Is my data structure compatible?
Any advice would be greatly appreciated.
You need to understand that in this sort of application, there are two separate places where code is executed.
On the "server", e.g. the computer where the database is running, or another computer that connects to it, there is an application that that is doing operations including querying the database, and providing the web application code to the user's web browser. This is also commonly referred to as "the backend".
On the "client" (the user's web browser), commonly referred to as "the frontend", the web application will get data from the backend via HTTP/S ("API calls").
In the sample code that you provided,the functionality in database.js belongs on the backend (on the server), and the code that you have in main.js belongs on the frontend (in the user's web browser).
Related
I am building a personal blog and chose Gatsby because of the obvious reasons(performance and easy to start out) and because I have some React background for the frontend. Also, I had built a simple app to create my content(html string) and store in a MongoDB database using express server. Now for the blog, I am just trying to pull the data from MongoDB using gatsby-source-mongodb plugin.
My MongoDB schemas have relationships. For instance, a 'Post' schema has a 'user' property which is an ObjectID that references a user from 'User' schema. My config for the gatsby-source-mongodb looks like:
{
resolve: 'gatsby-source-mongodb',
options: {
dbName: 'KathaDB',
collection: 'posts',
server: {
address: "somecluster",
port: 27017
},
auth: {
user: 'someuser',
password: 'somepasswd'
},
extraParams: {
replicaSet: 'test',
ssl: true,
authSource: 'admin',
retryWrites: true,
preserveObjectIds: true
}
}
}
I have a couple of questions:
When I query, I get all the properties from my 'Post' schema but I don't have 'user' property in the response. I don't know if it is due to the type of the property. I dug up a bit and found a similar issue here. It seems like they have solved the issue by preserving the ObjectID but i didn't even get the property that is of type ObjectID.
Another thing, does this plugin support relationships? For example, is it possible to get the 'user' data when its ObjectID is given?
It does.
MongoDB relies on ObjectIDs for relationships, so you might have to add preserveObjectIds: true to your plugin options:
{
resolve: "gatsby-source-mongodb",
options: {
dbName: "KathaDB",
collection: "posts",
server: {
address: "somecluster",
port: 27017,
},
auth: {
user: "someuser",
password: "somepasswd",
},
extraParams: {
replicaSet: "test",
ssl: true,
authSource: "admin",
retryWrites: true,
preserveObjectIds: true,
},
preserveObjectIds: true, // <= here
},
};
I'm unsure whether gatsby-source-mongodb creates the relationships out of the box (I don't think it does, if my memory is correct), but with the ObjectIds, you can create foreign-key relationships using GraphQL.
There are two ways of doing this in Gatsby:
Using mappings in gatsby-config.js
Using a GraphQL #link directive through Gatsby's schema customization (from v2.2)
I recommend the second option, since it's a more GraphQL way of doing things, and happens in gatsby-node.js where most node operations are taking place. However, if you're starting out with Gatsby and GraphQL, the first option might be easier to set up.
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());
});
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
[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
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