Skip to content

Commit

Permalink
lab_5: close #26, close #28; end lab5;
Browse files Browse the repository at this point in the history
  • Loading branch information
Enrico-git committed May 27, 2021
1 parent edf94a2 commit 8b3ea76
Show file tree
Hide file tree
Showing 6 changed files with 253 additions and 158 deletions.
18 changes: 16 additions & 2 deletions lab_5/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import mongoose from "mongoose";

try {
/*try {
await mongoose.connect(
'mongodb://localhost:27017/catalogue',
{
Expand All @@ -18,4 +18,18 @@ try {
} catch (error) {
//problems in establishing the connection
//handleError(error)
}
}*/

export const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection errro: '));
db.once('open', function () {
console.log('connected to db')
})

await mongoose.connect(
'mongodb://localhost:27017/catalogue',
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
76 changes: 76 additions & 0 deletions lab_5/graphql/resolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
'use strict'

import * as ProductService from "../services/ProductService.js";
import * as CommentService from "../services/CommentService.js";
import {typeDefs} from "./typedef.js";

export const resolvers = {
Query: {
product: async (parent, args, context, info) => {
const numOfComments = info.fieldNodes[0]
.selectionSet
.selections
.find(e => e.name.value == "comments")
?.arguments[0]
.value
.value
try{
return await ProductService.getProductById(args.id, numOfComments)
}catch (e) {
console.error(e)
throw e
}
},

products: async (parent, args, context, info) => {
const filter = args.filter
const sort = args.sort

const numOfComments = info.fieldNodes[0]
.selectionSet
.selections
.find(e => e.name.value == "comments")
?.arguments[0]
.value
.value
try{
return await ProductService.getProducts(filter, sort, numOfComments)
} catch (e) {
console.error(e)
throw e
}

}
},

Product: {
comments: async (product) => {
try {
return await CommentService.getCommentsById(product.comments)
} catch (e) {
console.error(e)
throw e
}
}
},

Mutation: {
createProduct: async (parent, args) => {
try{
return await ProductService.addProduct(args.createProductInput)
} catch (e) {
console.error(e)
throw e
}

},
createComment: async (parent, args) => {
try{
return await CommentService.addComment(args.createCommentInput, args.productId)
} catch (e) {
console.error(e)
throw e
}
}
}
}
79 changes: 79 additions & 0 deletions lab_5/graphql/typedef.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'use strict'

export const typeDefs = `
scalar DateTime
enum ProductCategory {
STYLE
FOOD
TECH
SPORT
}
enum SortingValue {
createdAt
price
}
enum SortingOrder {
asc
desc
}
input ProductCreateInput {
name : String!,
description : String,
price : Float! @constraint(min: 0),
category: ProductCategory!
}
input CommentCreateInput {
title: String!,
body: String,
stars: Int! @constraint(min: 0, max: 5)
}
type Comment {
_id: ID!,
title: String!,
body: String,
stars: Int!,
date: DateTime!
}
type Product {
_id: ID!,
name: String!,
createdAt: DateTime!,
description: String,
price: Float!,
category: ProductCategory!,
stars: Float,
comments (numberOfLastRecentComments: Int) : [Comment],
}
input FilterProductInput {
categories: [ProductCategory],
minStars: Int @constraint(min: 0, max: 5),
minPrice: Float @constraint(min: 0),
maxPrice: Float @constraint(min: 0)
}
input SortProductInput {
value: SortingValue!,
order: SortingOrder!
}
type Query {
products (filter: FilterProductInput, sort: SortProductInput) : [Product],
product (id: ID!) : Product,
}
type Mutation {
createProduct (createProductInput: ProductCreateInput!) : Product,
createComment (
createCommentInput: CommentCreateInput!,
productId: ID!
) : Comment
}
`
134 changes: 15 additions & 119 deletions lab_5/index.js
Original file line number Diff line number Diff line change
@@ -1,127 +1,23 @@
'use strict'
'use strict';

import express from 'express'
import {makeExecutableSchema} from 'graphql-tools'
import {graphqlHTTP} from 'express-graphql'
import './db.js'
import * as ProductService from './services/ProductService.js'
import * as CommentService from './services/CommentService.js'
import {graphqlHTTP} from "express-graphql";
import {makeExecutableSchema} from "graphql-tools";
import "./db.js"
import {typeDefs} from './graphql/typedef.js';
import {resolvers} from './graphql/resolver.js';
import {constraintDirective, constraintDirectiveTypeDefs} from 'graphql-constraint-directive';

const typeDefs = `
scalar DateTime
enum ProductCategory {
STYLE
FOOD
TECH
SPORT
}
enum SortingValue {
createdAt
price
}
enum SortingOrder {
asc
desc
}
input ProductCreateInput {
name : String!,
description : String,
price : Float!,
category: ProductCategory!
}
input CommentCreateInput {
title: String!,
body: String,
stars: Int!
}
type Comment {
_id: ID!,
title: String!,
body: String,
stars: Int!,
date: DateTime!
}
type Product {
_id: ID!,
name: String!,
createdAt: DateTime!,
description: String,
price: Float!,
comments (numberOfLastRecentComments: Int) : [Comment],
category: ProductCategory!,
stars: Float
}
input FilterProductInput {
categories: [ProductCategory],
minStars: Int,
minPrice: Float,
maxPrice: Float
}
input SortProductInput {
value: SortingValue!,
order: SortingOrder!
}
type Query {
products (filter: FilterProductInput, sort: SortProductInput) : [Product],
product (id: ID!) : Product,
hello: String
}
type Mutation {
createProduct (createProductInput: ProductCreateInput!) : Product,
createComment (
createCommentInput: CommentCreateInput!,
productId: ID!
) : Comment
}
`

const resolvers = {
Query: {
hello: () => {
return 'Hello Graphql....'
},
product: async (parent, args, context, info) => {
const numOfComments = info.fieldNodes[0]
.selectionSet
.selections
.find(e => e.name.value == "comments")
?.arguments[0]
.value
.value
return await ProductService.getProductById(args.id, numOfComments)
}
},
Product: {
comments: async (product) => {
return CommentService.getCommentsById(product.comments)
}
},
Mutation: {
createProduct: async (parent, args) => {
return await ProductService.addProduct(args.createProductInput)
},
createComment: async (parent, args) => {
return await CommentService.addComment(args.createCommentInput, args.productId)
}
}
}

const schema = makeExecutableSchema({typeDefs, resolvers})
const schema = makeExecutableSchema({
typeDefs: [constraintDirectiveTypeDefs, typeDefs],
resolvers,
schemaTransforms: [constraintDirective()]
})

const app = express()
const app = express();

app.use('/graphql', graphqlHTTP({schema, graphiql: true}))

app.listen(3000)
app.use('/graphql', graphqlHTTP({schema, graphiql:true}));

app.listen(3000);
13 changes: 11 additions & 2 deletions lab_5/services/CommentService.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ import Comments from '../models/Comments.js'
import {addCommentToProduct} from './ProductService.js'
import mongoose from 'mongoose'

import {db} from '../db.js'

export const getCommentsById = (comments) => {
return Comments.find({ _id : { $in : comments } } ).sort({ _id: -1 }).exec()
return Comments.find({_id: {$in: comments}}).sort({_id: -1}).exec()
}

export const addComment = async (comment, productID) => {
const session = await db.startSession()
session.startTransaction()
const commentID = mongoose.Types.ObjectId()
const createdComment = await Comments.create({_id: commentID, ...comment, date: new Date()})
await addCommentToProduct(productID, commentID, comment.stars)

if (! await addCommentToProduct(productID, commentID, comment.stars))
throw new Error("productID not found")

await session.commitTransaction()
session.endSession()
return createdComment
}
Loading

0 comments on commit 8b3ea76

Please sign in to comment.