This commit is contained in:
Riccardo
2021-08-29 10:39:39 +02:00
parent 2f119e43bd
commit 5368f40b04
8 changed files with 75 additions and 131 deletions

View File

@@ -21,10 +21,10 @@ const Appointment = (props) => {
onCompleted: () => history.push('/') onCompleted: () => history.push('/')
}) })
const updateAppointment = () => { // const updateAppointment = () => {
let path = `/update/${appointment._id}`; // let path = `/update/${appointment._id}`;
history.push(path); // history.push(path);
} // }
return ( return (
<div> <div>

View File

@@ -43,34 +43,34 @@ const CreateAppointment = () => {
start: formState.start, start: formState.start,
end: formState.end end: formState.end
}, },
// update: (cache, { data: { createAppointment } }) => { update: (cache, { data: { createAppointment } }) => {
// const take = APPOINTMENTS_PER_PAGE; const take = APPOINTMENTS_PER_PAGE;
// const skip = 0; const skip = 0;
// const orderBy = { createdAt: 'desc' }; const orderBy = { createdAt: 'desc' };
// const data = cache.readQuery({ const data = cache.readQuery({
// query: APPOINTMENTS_QUERY, query: APPOINTMENTS_QUERY,
// variables: { variables: {
// take, take,
// skip, skip,
// orderBy orderBy
// } }
// }); });
// cache.writeQuery({ cache.writeQuery({
// query: APPOINTMENTS_QUERY, query: APPOINTMENTS_QUERY,
// data: { data: {
// allAppointments: { allAppointments: {
// appointments: [createAppointment, ...data.allAppointments] appointments: [createAppointment, ...data.allAppointments]
// } }
// }, },
// variables: { variables: {
// take, take,
// skip, skip,
// orderBy orderBy
// } }
// }); });
// }, },
onCompleted: () => history.push('/') onCompleted: () => history.push('/')
}); });

View File

@@ -1,11 +1,11 @@
import React from 'react'; import React from 'react';
// import { useHistory } from 'react-router'; import { useHistory } from 'react-router';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
// import { AUTH_TOKEN } from '../../constants'; import { AUTH_TOKEN } from '../../constants';
const Header = () => { const Header = () => {
// const history = useHistory(); const history = useHistory();
// const authToken = localStorage.getItem(AUTH_TOKEN); const authToken = localStorage.getItem(AUTH_TOKEN);
return ( return (
<div className="flex pa1 justify-between nowrap orange"> <div className="flex pa1 justify-between nowrap orange">
<div className="flex flex-fixed black"> <div className="flex flex-fixed black">
@@ -20,7 +20,7 @@ const Header = () => {
{/* <div className="flex flex-fixed"> {/* <div className="flex flex-fixed">
<Link to="/search" className="ml1 no-underline black">Search</Link> <Link to="/search" className="ml1 no-underline black">Search</Link>
</div> */} </div> */}
{/* <div className="flex flex-fixed"> <div className="flex flex-fixed">
{authToken ? ( {authToken ? (
<div className="ml1 pointer black" <div className="ml1 pointer black"
onClick={() => { onClick={() => {
@@ -31,7 +31,7 @@ const Header = () => {
) : ( ) : (
<Link to="/login" className="ml1 no-underline black">Login</Link> <Link to="/login" className="ml1 no-underline black">Login</Link>
)} )}
</div> */} </div>
</div> </div>
); );
}; };

View File

@@ -10,7 +10,6 @@ import fs from 'fs';
import path from 'path'; import path from 'path';
import cors from 'cors'; import cors from 'cors';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
const { APP_SECRET } = require('../utils');
const moduleURL = new URL(import.meta.url); const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname); const __dirname = path.dirname(moduleURL.pathname);
@@ -20,7 +19,7 @@ const pubsub = new PubSub();
dotenv.config(); dotenv.config();
function getTokenPayload(token) { function getTokenPayload(token) {
return jwt.verify(token, APP_SECRET); return jwt.verify(token, process.env.APP_SECRET);
} }
function getUserId(req, authToken) { function getUserId(req, authToken) {
@@ -58,17 +57,7 @@ const server = new ApolloServer({
// schema, // schema,
cors: true, cors: true,
playground: process.env.NODE_ENV === 'development' ? true : false, playground: process.env.NODE_ENV === 'development' ? true : false,
context: ({ req }) => { context: ({ req }) => ({
// if (!db) {
// try {
// if (!dbClient.isConnected()) await dbClient.connect()
// mongo = dbClient.db('Calendar') // database name
// console.log(db);
// } catch (e) {
// console.log('--->error while connecting with graphql context (db)', e)
// }
return {
...req, ...req,
mongoose, mongoose,
pubsub, pubsub,
@@ -76,25 +65,24 @@ const server = new ApolloServer({
req && req.headers.authorization req && req.headers.authorization
? getUserId(req) ? getUserId(req)
: null : null
}),
subscriptions: {
onConnect: (connectionParams) => {
if (connectionParams.authToken) {
return {
mongoose,
userId: getUserId(
null,
connectionParams.authToken
)
}; };
} else {
return {
mongoose
};
}
}
}, },
// subscriptions: {
// onConnect: (connectionParams) => {
// if (connectionParams.authToken) {
// return {
// mongoose,
// userId: getUserId(
// null,
// connectionParams.authToken
// )
// };
// } else {
// return {
// mongoose
// };
// }
// }
// },
introspection: true, introspection: true,
tracing: true, tracing: true,
path: '/', path: '/',
@@ -118,36 +106,3 @@ server.applyMiddleware({
app.listen({ port: process.env.PORT }, () => { app.listen({ port: process.env.PORT }, () => {
console.log(`Server listening on port ${process.env.PORT}`); console.log(`Server listening on port ${process.env.PORT}`);
}); });
// const { graphqlHTTP } = require('express-graphql');
// const mongoose = require("mongoose");
// const graphqlSchema = require("./graphql/schema/schema")
// const appointmentResolvers = require("./graphql/resolvers/appointment")
// const userResolvers = require("./graphql/resolvers/user")
// var MongoClient = require('mongodb', { useUnifiedTopology: true }).MongoClient;
// // import { MongoClient } from 'mongodb'
// const Query = require('./resolvers/Query');
// const Mutation = require('./resolvers/Mutation');
// const Subscription = require('./resolvers/Subscription');
// const User = require('./resolvers/User');
// const Appointment = require('./resolvers/Appointment');
// const Follow = require('./resolvers/Follow');
// const fs = require('fs');
// const path = require('path');
// const { getUserId } = require('./utils');
// const graphqlResolvers = {
// appointmentResolvers,
// userResolvers
// };
// // const resolvers = {
// // Query,
// // Mutation,
// // Subscription,
// // User,
// // Appointment,
// // Follow
// // };

View File

@@ -1,6 +1,7 @@
import Appointment from './models/appointment.js'; import Appointment from './models/appointment.js';
import User from './models/user.js'; import User from './models/user.js';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { createAppointment } from './resolvers/Mutation';
export const resolvers = { export const resolvers = {
Query: { Query: {
@@ -30,11 +31,7 @@ export const resolvers = {
}; };
}, },
async login(parent, args, context) { async login(parent, args) {
console.log(context);
const { userId } = context;
console.log(userId);
const user = await User.findOne({ const user = await User.findOne({
email: args.email email: args.email
}); });
@@ -55,15 +52,9 @@ export const resolvers = {
}, },
async createAppointment(parent, args, context) { async createAppointment(parent, args, context) {
console.log(context); return await createAppointment(parent, args, context);
const { userId } = context;
console.log("userID", userId);
args.deleted = false;
args.createdBy = userId;
return await Appointment.create(args);
}, },
async updateAppointment(parent, args) { async updateAppointment(parent, args) {
console.log(args);
return await Appointment.findOneAndUpdate({ return await Appointment.findOneAndUpdate({
args args
}, args, { }, args, {

View File

@@ -1,19 +1,16 @@
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { APP_SECRET } = require('../utils'); import dotenv from 'dotenv';
import appointment from '../models/appointment';
function createAppointment(parent, args, context) { dotenv.config();
async function createAppointment(parent, args, context) {
const { userId } = context; const { userId } = context;
args.deleted = false;
const newAppointment = context.mongo.appointment.create({ args.createdBy = userId;
data: { console.log(parent, args, context);
title: args.title, return await appointment.create(args);
description: args.description,
createdBy: { connect: { id: userId } }
}
});
return newAppointment;
} }
async function signup(parent, args, context) { async function signup(parent, args, context) {
@@ -22,7 +19,7 @@ async function signup(parent, args, context) {
data: { ...args, password } data: { ...args, password }
}); });
const token = jwt.sign({ userId: user.id }, APP_SECRET); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET);
return { return {
token, token,
@@ -46,7 +43,7 @@ async function login(parent, args, context) {
throw new Error('Invalid password'); throw new Error('Invalid password');
} }
const token = jwt.sign({ userId: user.id }, APP_SECRET); const token = jwt.sign({ userId: user.id }, process.env.APP_SECRET);
return { return {
token, token,

View File

@@ -59,7 +59,7 @@ input UserInput {
username: String! username: String!
email: String! email: String!
password: String! password: String!
appointments: [Appointment!]! appointments: [AppointmentInput!]!
} }
type AuthPayload { type AuthPayload {
token: String token: String
@@ -75,7 +75,7 @@ type Appointment {
start: DateTime! start: DateTime!
end: DateTime! end: DateTime!
deleted: Boolean deleted: Boolean
user: User createdBy: User
# follows: [Follow!]! # follows: [Follow!]!
} }
input AppointmentInput { input AppointmentInput {

View File

@@ -1,8 +1,10 @@
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
const APP_SECRET = 'GraphQL-is-aw3some'; import dotenv from 'dotenv';
dotenv.config();
function getTokenPayload(token) { function getTokenPayload(token) {
return jwt.verify(token, APP_SECRET); return jwt.verify(token, process.env.APP_SECRET);
} }
function getUserId(req, authToken) { function getUserId(req, authToken) {
@@ -25,6 +27,5 @@ function getUserId(req, authToken) {
} }
module.exports = { module.exports = {
APP_SECRET,
getUserId getUserId
}; };