Skip to content

Instantly share code, notes, and snippets.

View kluu1's full-sized avatar

Kevin Luu kluu1

  • Atlanta, GA
View GitHub Profile
service: serverless-graphql
plugins:
- serverless-offline
provider:
name: aws
runtime: nodejs12.x
stage: ${opt:stage, 'dev'}
region: us-east-1
@kluu1
kluu1 / app.js
Last active March 26, 2020 19:22
const { ApolloServer, AuthenticationError } = require('apollo-server');
const typeDefs = require('./graphql/typeDefs');
const resolvers = require('./graphql/resolver');
const getUser = require('./auth');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
// Get the user token from the headers
@kluu1
kluu1 / auth.js
Last active March 26, 2020 19:44
const { AuthenticationError } = require('apollo-server');
// This file is where you would implement your authentication strategy
// Eg. AWS Cognito, Passport, JWT, etc.
const getUser = (token) => {
if (token !== '1234567890') {
throw new AuthenticationError('Invalid token');
}
const user = {
const books = require('../data');
const resolvers = {
Query: {
books: (_, args, { user }) => {
if (user && user.role !== 'admin') {
throw new Error('Not Authorized');
}
return books
...
const user = {
id: 1,
username: 'demouser',
role: 'nonadmin'
}
...
@kluu1
kluu1 / app.js
Last active March 30, 2020 19:24
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const keys = require('./configs/keys');
require('./models/Article');
require('./utils/redis');
const app = express();
const port = process.env.PORT || 3000;
const mongoose = require('mongoose');
const { Schema } = mongoose;
const articleSchema = new Schema({
title: String,
author: String,
content: String,
createdAt: { type: Date, default: Date.now },
});
module.exports = {
MONGO_URI: 'YOUR_MONGODB_CONNECTION_STRING_GOES_HERE',
REDIS_URI: 'YOUR_REDIS_CONNECTION_STRING_GOES_HERE'
};
@kluu1
kluu1 / redis.js
Last active March 30, 2020 20:18
const mongoose = require('mongoose');
const redis = require('redis');
const util = require('util');
const keys = require('../configs/keys')
const client = redis.createClient(keys.REDIS_URL);
client.hget = util.promisify(client.hget);
// create reference for .exec
const exec = mongoose.Query.prototype.exec;
const mongoose = require('mongoose');
const Article = mongoose.model('Article');
module.exports = app => {
app.get('/api/articles', async (req, res) => {
const articles = await Article.find().cache({ expire: 10 });
res.json(articles);
});