Some progress

This commit is contained in:
Riccardo
2021-01-03 16:49:26 +01:00
parent 8dd59ae64b
commit e72890fe28
15 changed files with 158 additions and 382 deletions

View File

@@ -1,31 +0,0 @@
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const appointmentSchema = new Schema(
{
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
timeStart: {
type: Date,
required: true,
},
timeEnd: {
type: Date,
required: true,
},
},
{ timestamps: true }
)
module.exports = mongoose.model("Appointment", appointmentSchema)

View File

@@ -1,36 +0,0 @@
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const userSchema = new Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
isActive: {
type: Boolean,
required: true,
default: 1
},
},
{ timestamps: true }
)
module.exports = mongoose.model("User", userSchema)

View File

@@ -1,36 +0,0 @@
// const { default: Appointment } = require("../../../../client/src/components/Appointment")
const { newAppointment } = require("../../resolvers/Subscription")
const Appointment = require("../models/appointment")
module.exports = {
findAppointments: async () => {
try {
const appointmentsFetched = await Appointment.find()
return appointmentsFetched.map(appointment => {
return {
...this.appointment._doc,
_id: appointment.id,
createdAt: new Date(appointment._doc.createdAt).toISOString(),
}
})
} catch (error) {
throw error
}
},
createAppointment: async args => {
try {
const { title, description, timeStart, timeEnd } = args.appointment
const appointment = new Appointment({
title,
description,
timeStart,
timeEnd
})
const newAppointment = await appointment.save()
return { ...newAppointment._doc, _id: newAppointment.id }
} catch (error) {
throw error
}
},
}

View File

@@ -1,36 +0,0 @@
// const { default: Appointment } = require("../../../../client/src/components/Appointment")
// const { newUser } = require("../../resolvers/Subscription")
const User = require("../models/user")
module.exports = {
findUsers: async () => {
try {
const usersFetched = await User.find()
return usersFetched.map(user => {
return {
...this.user._doc,
_id: user.id,
createdAt: new Date(user._doc.createdAt).toISOString(),
}
})
} catch (error) {
throw error
}
},
createUser: async args => {
try {
const { firstName, lastName, email, isActive } = args.user
const user = new User({
firstName,
lastName,
email,
isActive
})
const newUser = await user.save()
return { ...newUser._doc, _id: newUser.id }
} catch (error) {
throw error
}
},
}

View File

@@ -1,53 +0,0 @@
const { buildSchema } = require("graphql")
module.exports = buildSchema(`
type User {
_id: ID!
firstName: String!
lastName: String!
email: String!
password: String!
isActive: Boolean!
}
input UserInput {
firstName: String!
lastName: String!
email: String!
password: String!
isActive: Boolean!
}
type Appointment {
_id: ID!
title: String!
description: String!
timeStart: Date!
timeEnd: Date!
createdAt: String!
}
input AppointmentInput {
title: String!
description: String!
timeStart: Date!
timeEnd: Date!
}
type Query {
findAppointments:[Appointment!]
findUsers:[User!]!
}
type Mutation {
createAppointment(appointment:AppointmentInput): Appointment
createUser(user:UserInput): User
}
schema {
query: Query
mutation: Mutation
}
scalar Date
`)

View File

@@ -1,17 +1,37 @@
import dotenv from 'dotenv';
import express from 'express';
import dotenv from 'dotenv';
import { graphqlHTTP } from 'express-graphql';
import { ApolloServer, PubSub } from 'apollo-server-express';
import mongoose from 'mongoose';
import schema from './schema.js';
import './utils/db.js';
import schema from './schema/index.js';
import fs from 'fs';
import path from 'path';
const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname);
const app = express();
const pubsub = new PubSub();
const PORT = 4000;
dotenv.config();
const app = express();
const pubsub = new PubSub();
app.get('/', (req, res) => {
res.json({
msg: 'Welcome to GraphQL'
})
});
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true
}));
const server = new ApolloServer({
schema,
typeDefs: fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
),
cors: true,
playground: process.env.NODE_ENV === 'development' ? true : false,
context: async ({ req }) => {
@@ -27,30 +47,30 @@ const server = new ApolloServer({
return {
...req,
mongoose,
pubsub,
userId:
req && req.headers.authorization
? getUserId(req)
: null
}
},
subscriptions: {
onConnect: (connectionParams) => {
if (connectionParams.authToken) {
return {
mongoose,
userId: getUserId(
null,
connectionParams.authToken
)
};
} else {
return {
mongoose
};
}
// pubsub,
// userId:
// req && req.headers.authorization
// ? getUserId(req)
// : null
}
},
// subscriptions: {
// onConnect: (connectionParams) => {
// if (connectionParams.authToken) {
// return {
// mongoose,
// userId: getUserId(
// null,
// connectionParams.authToken
// )
// };
// } else {
// return {
// mongoose
// };
// }
// }
// },
introspection: true,
tracing: true,
path: '/',
@@ -78,6 +98,9 @@ app.listen({ port: process.env.PORT }, () => {
// const { ApolloServer, PubSub } = require('apollo-server');
// // const { Cors } = require('cors');
// // const { Express } = require('express');

View File

@@ -1,43 +0,0 @@
import mongoose from 'mongoose';
import timestamps from 'mongoose-timestamp';
import { composeWithMongoose } from 'graphql-compose-mongoose';
export const AppointmentSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
timeStart: {
type: Date,
required: true,
},
timeEnd: {
type: Date,
required: true,
},
},
{
collection: 'appointment',
}
);
AppointmentSchema.plugin(timestamps);
AppointmentSchema.index({ createdAt: 1, updatedAt: 1 });
export const Appointment = mongoose.model('Appointment', AppointmentSchema);
export const AppointmentTC = composeWithMongoose(Appointment);

View File

@@ -0,0 +1,12 @@
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true
},
qty: {
type: Number
}
});
export default mongoose.model('product', ProductSchema);

View File

@@ -1,45 +0,0 @@
import mongoose from 'mongoose';
import timestamps from 'mongoose-timestamp';
import { composeWithMongoose } from 'graphql-compose-mongoose';
export const UserSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
lowercase: true,
unique: true,
required: true,
},
isActive: {
type: Boolean,
required: true,
default: 1
},
},
{
collection: 'users',
}
);
UserSchema.plugin(timestamps);
UserSchema.index({ createdAt: 1, updatedAt: 1 });
export const User = mongoose.model('User', UserSchema);
export const UserTC = composeWithMongoose(User);

41
server/src/resolvers.js Normal file
View File

@@ -0,0 +1,41 @@
import Product from './models/product.js';
// import User from './resolvers/User.js';
// import Appointment from './resolvers/Appointment.js';
// import Follow from './resolvers/Follow.js';
// import Query from './resolvers/Query.js';
// import Mutation from './resolvers/Mutation.js';
// import Subscription from './resolvers/Subscription.js';
export const resolvers = {
Query: {
async allProducts() {
return await Product.find();
},
// async feed(parent, args, context, info) {
// const where = args.filter
// ? {
// OR: [
// { title: { contains: args.filter } },
// { description: { contains: args.filter } }
// ]
// }
// : {};
// console.log(context.mongo);
// const appointments = await context.mongo.appointment.findMany({
// where,
// skip: args.skip,
// take: args.take,
// orderBy: args.orderBy
// });
// const count = await context.mongo.appointment.count({ where });
// return {
// id: 'main-feed',
// appointments,
// count
// };
// }
}
};

View File

@@ -6,6 +6,7 @@ type Query {
take: Int
orderBy: AppointmentOrderByInput
): Feed!
allProducts: [Product]
# users: [User!]!
}
@@ -64,6 +65,12 @@ type Appointment {
createdAt: DateTime!
}
type Product {
id: ID!
title: String!
qty: Integer
}
type Follow {
id: ID!
appointment: Appointment!
@@ -81,4 +88,5 @@ enum Sort {
desc
}
scalar Integer
scalar DateTime

45
server/src/schema.js Normal file
View File

@@ -0,0 +1,45 @@
import {
makeExecutableSchema
} from 'graphql-tools';
import {
resolvers
} from './resolvers.js';
import fs from 'fs';
import path from 'path';
const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname);
const typeDefs = fs.readFileSync(
path.join(__dirname, 'schema.graphql'),
'utf8'
);
const schema = makeExecutableSchema({
typeDefs,
// resolvers
});
export default schema;
// import {
// makeExecutableSchema
// } from 'graphql-tools';
// import {
// resolvers
// } from './resolvers.js';
// const typeDefs = `
// type Product {
// _id: ID!
// title: String!
// qty: Int
// }
// type Query {
// allProducts: [Product]
// }
// `;
// const schema = makeExecutableSchema({
// typeDefs,
// resolvers
// });
// export default schema;

View File

@@ -1,51 +0,0 @@
import { Appointment, AppointmentTC } from '../models/appointment.js';
async function feed(parent, args, context, info) {
const where = args.filter
? {
OR: [
{ title: { contains: args.filter } },
{ description: { contains: args.filter } }
]
}
: {};
console.log(context.mongo);
const appointments = await context.mongo.appointment.findMany({
where,
skip: args.skip,
take: args.take,
orderBy: args.orderBy
});
const count = await context.mongo.appointment.count({ where });
return {
id: 'main-feed',
appointments,
count
};
}
const AppointmentQuery = {
appointmentById: AppointmentTC.getResolver('findById'),
appointmentByIds: AppointmentTC.getResolver('findByIds'),
appointmentOne: AppointmentTC.getResolver('findOne'),
appointmentMany: AppointmentTC.getResolver('findMany'),
appointmentCount: AppointmentTC.getResolver('count'),
appointmentConnection: AppointmentTC.getResolver('connection'),
appointmentPagination: AppointmentTC.getResolver('pagination'),
};
const AppointmentMutation = {
appointmentCreateOne: AppointmentTC.getResolver('createOne'),
appointmentCreateMany: AppointmentTC.getResolver('createMany'),
appointmentUpdateById: AppointmentTC.getResolver('updateById'),
appointmentUpdateOne: AppointmentTC.getResolver('updateOne'),
appointmentUpdateMany: AppointmentTC.getResolver('updateMany'),
appointmentRemoveById: AppointmentTC.getResolver('removeById'),
appointmentRemoveOne: AppointmentTC.getResolver('removeOne'),
appointmentRemoveMany: AppointmentTC.getResolver('removeMany'),
};
export { AppointmentQuery, AppointmentMutation };

View File

@@ -1,24 +0,0 @@
import { User, UserTC } from '../models/user.js';
const UserQuery = {
userById: UserTC.getResolver('findById'),
userByIds: UserTC.getResolver('findByIds'),
userOne: UserTC.getResolver('findOne'),
userMany: UserTC.getResolver('findMany'),
userCount: UserTC.getResolver('count'),
userConnection: UserTC.getResolver('connection'),
userPagination: UserTC.getResolver('pagination'),
};
const UserMutation = {
userCreateOne: UserTC.getResolver('createOne'),
userCreateMany: UserTC.getResolver('createMany'),
userUpdateById: UserTC.getResolver('updateById'),
userUpdateOne: UserTC.getResolver('updateOne'),
userUpdateMany: UserTC.getResolver('updateMany'),
userRemoveById: UserTC.getResolver('removeById'),
userRemoveOne: UserTC.getResolver('removeOne'),
userRemoveMany: UserTC.getResolver('removeMany'),
};
export { UserQuery, UserMutation };