Skip to content

Instantly share code, notes, and snippets.

@franckc
Created August 13, 2018 05:59
Show Gist options
  • Save franckc/d3a16788168f6529c2c36d6fb0e1792f to your computer and use it in GitHub Desktop.
Save franckc/d3a16788168f6529c2c36d6fb0e1792f to your computer and use it in GitHub Desktop.
Apollo server prototype
const { ApolloServer, gql } = require('apollo-server');
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client( {
hosts: [
'http://192.168.1.44:9200/'
]
});
const { Pool } = require('pg')
const pool = new Pool(
{
host: '192.168.1.44',
database: 'graphql',
user: 'franck',
password: 'franck',
})
async function allListings() {
return pool.query('SELECT * FROM listings', []).then(function(res) {
console.log(`DB returned ${res.rows.length} rows`)
let listings = []
res.rows.forEach(function(row){
let listing = {
id: row.id,
}
listings.push(listing)
})
return listings
})
}
async function searchListings(query) {
return client.search({
index: 'origin',
type: 'listing',
body: {
query: {
match: { "description": query }
},
}
}).then(function(response) {
console.log(`Elastic returned ${response.hits.hits.length} hits`)
let listings = []
response.hits.hits.forEach(function(hit){
let listing = {
id: hit._id,
name: hit._source.name,
description: hit._source.description,
price: hit._source.price,
}
listings.push(listing)
})
return listings
})
}
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
# This "Listing" type can be used in other type declarations.
type Listing {
id: String
name: String
description: String
price: Float
}
# The "Query" type is the root of all GraphQL queries.
# (A "Mutation" type will be covered later on.)
type Query {
searchListings(query: String!): [Listing],
allListings: [Listing],
}
`;
// Resolvers define the technique for fetching the types in the
// schema.
const resolvers = {
Query: {
searchListings(root, args, context, info) {
return searchListings(args.query)
},
allListings(root, args, context, info) {
return allListings()
},
},
};
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({ typeDefs, resolvers });
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment