Is there any example code implementing GraphQL on NodeJS without using any other middleware like Express, Apollo, etc. Just pure NodeJS http server with GraphQL, and any SQL db.
upd: If someone interested, you can check out my implementation on github - pureGraphQLapi
Nothing prevents you from using Node.js and GraphQL only ; you will be writing a little more code though.
Create your HTTP Server with Node.js only
Listen to incoming requests and use POST json body (for example) to pass query and variables to graphql function
Related
Suppose I am building a backend api which can be consumed using rest as well as graphql.
My tech stack : Node.js, Express.js,
Suppose I have the following rest resource paths
/user
/post
/comment
Now. I also want to run a graphql server on a different resource path say /graphql on the same server. Is this possible ? If so, then how ?
I have created a graphql server using ApolloServer
We use axios for http requests such as get, post, etc.
We use express for the same purpose also.
However according to what I read, they are for different purposes.
Please explain how.
PS: If you explain it by giving an example, it would be great!
You can think of express.js as a warehouse:
app.get('/item/:name', async function (req, res) {
res.send(await findItemByName(req.params.name));
});
If you want to get an item, for example a pencil, from this warehouse, you can use axios.js.
axios.get('/item/pencil')
Axios is used to send a web request whereas express is used to listen and serve these web requests.
In simple words, express is used to respond to the web requests sent by axios.
If you know about the fetch() method in javascript, axios is just an alternative to fetch().
I would say that express is used to create HTTP servers. So the server runs somewhere and responds to a request.
Axios is an HTTP client. It creates requests!
In very simple words axios is just passing the web request to the server-side (express). They basically work together (axios -> express -> DB)
I would like to build an application and its recommended to use GraphQl for API,
I am not sure which platform to select and what are the differences.
apollo server vs express-graphql
I need to use TypeScript for the project too.
Any good Idea would be appreciated.
Below is the now deleted section from the apollo-server README comparing apollo-server to express-graphql.
Note that some of these arguments do not apply anymore e.g. express-grapqhl is now written in TypeScript. Hence the removal of this section from the README.
One observation is that apollo-server is too bloated, and is slowly showing a lack of maintenance. I would go with express-graphql instead if I were to pick one today. But this is personal preference and you should do your own due diligence.
There's also a community-maintained Koa port of express-graphql, called koa-graphql. Using either express-graphql, or koa-graphql, combined with something like envelop, you can achieve everything, if not more, the Apollo "ecosystem" provides in a more modular manner.
Comparison with express-graphql
Both Apollo Server and
express-graphql are
GraphQL servers for Node.js, built on top of the graphql-js
reference implementation, but
there are a few key differences:
express-graphql works with Express and Connect, Apollo Server supports Express, Connect, Hapi, Koa and Restify.
Compared to express-graphql, Apollo Server has a simpler interface and supports exactly one way of passing queries.
Apollo Server separates serving GraphiQL (an in-browser IDE for
exploring GraphQL) from responding to GraphQL requests.
express-graphql contains code for parsing HTTP request bodies, Apollo Server leaves that to standard packages like body-parser.
Apollo Server includes an OperationStore to easily manage whitelisting.
Apollo Server is built with TypeScript.
application/graphql requests
express-graphql supports the application/graphql Content-Type for
requests, which is an alternative to application/json request with
only the query part sent as text. In the same way that we use
bodyParser.json to parse application/json requests for
apollo-server, we can use bodyParser.text plus one extra step in
order to also parse application/graphql requests. Here's an example
for Express:
'body-parser'; import { graphqlExpress } from 'apollo-server-express';
const myGraphQLSchema = // ... define or import your schema here!
const helperMiddleware = [
bodyParser.json(),
bodyParser.text({ type: 'application/graphql' }),
(req, res, next) => {
if (req.is('application/graphql')) {
req.body = { query: req.body };
}
next();
} ];
express()
.use('/graphql', ...helperMiddleware, graphqlExpress({ schema: myGraphQLSchema }))
.listen(3000); ```
Express-GraphQL is a piece of middleware, to quickly setup a GraphQL Server, either with Express, or any web-framework that supports middleware.
Apollo-server is a package that will sit on an existing node server and parse the GraphQL queries. (Very similar to express-graphql) You can use it with express, Koa etc.
My recommendation is use Graphql-yoga as it's built with apollo-server and express-graphql. And it's built and maintained by the Prisma Team.
I suggest using apollo-server-express over express-graphql. They are very similar, but apollo-server-express has more bells and whistles all while having a simpler and clearer API IMO.
The biggest improvement in apollo-server-express, for me, is the playground: https://github.com/prisma/graphql-playground
The playground is better than express-graphql's graphiql for several reasons, but one big one is that it allows you to put HTTP headers in the request, which is more appropriate for handling session.
www.graphqlbin.com will allow you to use the playground on any endpoint which does not have cors. If you have cors, then you will need to run playground directly from your server.
Here is a sample of code to get you started:
const { ApolloServer } = require('apollo-server-express')
const graphqlServer = new ApolloServer({
schema,
introspection: true,
playground: true,
})
graphqlServer.applyMiddleware({
app
})
What's the difference between creating a server using http module and creating a server using express framework in node js?
Thanks.
Ultimately, express uses node's http api behind the scenes.
express framework
The express framework provides an abstraction layer above the vanilla http module to make handling web traffic and APIs a little easier. There's also tons of middleware available for express (and express-like) frameworks to complete common tasks such as: CORS, XSRF, POST parsing, cookies etc.
http api
The http api is very simple and is used to to setup and manage incoming/outgoing ,HTTP connections. Node does most of the heavy lifting here but it does provide things you'll commonly see throughout most node web framework such as: request/response objects etc.
Express uses the http module under the hood, app.listen() returns an instance of http. You would use https.createServer if you needed to serve your app using HTTPS, as app.listen only uses the http module.
Here's the source for app.listen so you can see the similarities.:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
I am trying to build a test app for learning Node.js. I came from wordpress background and Apache has setup most of backend logics for me. But now, I have to build my own. I have a question about how to serve JSON files from server side to client side. What is the workflow -- Backbone.js handle all client side Data manipulation, send/save/get/fetch from couchDB, serve JSON object from NODE.js backend?
I am using Express Microframework for building HTTP server, installed the Cradle middleware for access CouchDB NoSQL database. I successfully posted the data from Client side HTML (Jade template engine) to the CouchDB Database/Document and able to retrieve those data back from Server through Cradle middleware. Things work out great. But it was all done by Backend.
I want to use Backbone.js for my client side Javascript. Backbone.js is looking for JSON object which send back from the HTTP server. Cradle Middleware is able to create JSON object but only send them directly to the Jade Template, I could use Jade syntax for loop to iterate over the data object but it still not meet what I want for Backbone.js handle all the data entry. I realize that I need to get JSON obj via ajax ( either a file generated by HTTP then send back to the client OR send straight object to the client ). Cradle Middleware could not do that.
I did more research on this questions. I tried CouchApp, it does what I need. Using the Backbone.js to handling all the data, send/save/fetch data from CouchDB database. But it is a running in CouchApp, it is not an Express Node.js workflow. ( Maybe I am wrong or just do not how it work )
I tried backbone-couchdb.js. I read through the Details and still do not know it is going to help me to get what I want. ( Maybe need more tutorial or code example ). I am still thinking that I need a Backbone CouchDB driver to connect those two and somehow serving them by NODE.js backend.
Is there anybody who could tell me about how JSON file is being served by Node.js, how backbone.js interact with data save/fetch/get from CouchDB? What is the best practice / workflow? Other good resources, code examples, useful tools?
Cradle Middleware is able to create JSON object but only send them directly to the Jade Template
This is incorrect. You can just send the json back without rendering a template.
function(req, res, next){
db.view('user/byUsername', { key: 'luke' }, function (err, doc) {
res.send(doc); // or res.json(doc);
});
}