models

package
v0.0.0-...-dd12240 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2019 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CartConfig = graphql.ObjectConfig{
	Name: "Cart",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Items": &graphql.Field{
			Type:        graphql.NewList(ItemSchema),
			Description: "Getting the list of items",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {

				cart, ok := params.Source.(Cart)
				if !ok {
					return nil, nil
				}
				DB.First(&cart).Related(&cart.Items, "Items")
				return cart.Items, nil
			},
		},
		"Total": &graphql.Field{
			Type: graphql.Float,
		},
	},
}

CartConfig is the config for the Cart object

CartSchema is the schema for the Cart model

View Source
var CategoryArgumentConfig = graphql.FieldConfigArgument{
	"Name": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.String),
	},
	"Description": &graphql.ArgumentConfig{
		Type: graphql.String,
	},
}

CategoryArgumentConfig is argument config required for the category

View Source
var CategoryConfig = graphql.ObjectConfig{
	Name: "Category",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Name": &graphql.Field{
			Type: graphql.String,
		},
		"Description": &graphql.Field{
			Type: graphql.String,
		},

		"Products": &graphql.Field{
			Type: graphql.NewList(ProductSchema),
		},
	},
}

CategoryConfig is the config for the category object

CategorySchema is the schema of the category model

View Source
var CreateCart = &graphql.Field{
	Type:        CartSchema,
	Description: "Create new Cart",
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		newCart := Cart{}

		DB.Create(&newCart)

		return newCart, nil
	},
}

CreateCart for creating an Order

View Source
var CreateCategory = &graphql.Field{
	Type:        CategorySchema,
	Description: "Create new Category",
	Args:        CategoryArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		name, _ := params.Args["Name"].(string)
		description, okd := params.Args["Description"]

		newCategory := Category{
			Name: name,
		}
		if okd {
			newCategory.Description = description.(string)
		}
		DB.Create(&newCategory)

		return newCategory, nil
	},
}

CreateCategory for creating a Category

View Source
var CreateItem = &graphql.Field{
	Type:        ItemSchema,
	Description: "Create new Item",
	Args:        ItemArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		p, _ := params.Args["Product"]
		price, okp := params.Args["Price"]
		qty, _ := params.Args["Qty"]

		newItem := Item{
			Qty: qty.(int),
		}

		DB.Where(p.(int)).Find(&newItem.Product)

		if okp {
			newItem.Price = price.(float64)
		} else {
			newItem.Price = newItem.Product.Price
		}

		DB.Create(&newItem)

		return newItem, nil
	},
}

CreateItem for creating an Item

View Source
var CreateOrder = &graphql.Field{
	Type:        OrderSchema,
	Description: "Create new Order",
	Args:        CreateOrderArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		name, _ := params.Args["Name"].(string)
		total, okt := params.Args["Total"]
		date, okd := params.Args["Date"]

		newOrder := Order{Name: name}

		if okt {
			newOrder.Total = total.(float64)
		}
		if okd {
			newOrder.Date = date.(time.Time)
		} else {

			newOrder.Date = time.Now()
		}

		DB.Create(&newOrder)

		return newOrder, nil
	},
}

CreateOrder for creating an Order

View Source
var CreateOrderArgumentConfig = graphql.FieldConfigArgument{
	"Name": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.String),
	},
	"Total": &graphql.ArgumentConfig{
		Type: graphql.Float,
	},
	"Date": &graphql.ArgumentConfig{
		Type: graphql.DateTime,
	},
}

CreateOrderArgumentConfig is argument config required for the Order

View Source
var CreateProduct = &graphql.Field{
	Type:        ProductSchema,
	Description: "Create new Product",
	Args:        ProductArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		name, _ := params.Args["Name"].(string)
		brand, okb := params.Args["Brand"]
		description, okd := params.Args["Description"]
		tags, okt := params.Args["Tags"]
		price, _ := params.Args["Price"].(float64)
		image, oki := params.Args["Image"]

		newProduct := Product{
			Name:  name,
			Price: price,
		}
		if okb {
			newProduct.Brand = brand.(string)
		}
		if okd {
			newProduct.Description = description.(string)
		}
		if okt && tags != nil {
			DB.Where(tags.([]int)).Find(&newProduct.Tags)
		}
		if oki {
			newProduct.Image = image.(string)
		}
		DB.Create(&newProduct)

		return newProduct, nil
	},
}

CreateProduct for creating a Product

View Source
var CreateTag = &graphql.Field{
	Type:        TagSchema,
	Description: "Create new Tag",
	Args: graphql.FieldConfigArgument{
		"Name": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		name, _ := params.Args["Name"].(string)

		newTag := Tag{
			Name: name,
		}
		DB.Create(&newTag)

		return newTag, nil
	},
}

CreateTag for creating a Tag

View Source
var CreateUser = &graphql.Field{
	Type:        UserSchema,
	Description: "Create new user",
	Args: graphql.FieldConfigArgument{
		"Number": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
		"Password": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
		"Name": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		number, _ := params.Args["Number"].(string)
		password, _ := params.Args["Password"].(string)
		name, _ := params.Args["Name"].(string)

		newUser := User{
			Number:   number,
			Password: password,
			Name:     name,
		}

		newCart := Cart{}
		DB.Create(&newCart)

		newUser.Cart = newCart

		DB.Create(&newUser)

		return newUser, nil
	},
}

CreateUser for creating a user

View Source
var DB *gorm.DB

DB is the data base connection instance to be accessed globally

View Source
var ItemArgumentConfig = graphql.FieldConfigArgument{
	"Product": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Int),
	},
	"Price": &graphql.ArgumentConfig{
		Type: graphql.Float,
	},
	"Qty": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Int),
	},
}

ItemArgumentConfig is argument config required for the Item

View Source
var ItemConfig = graphql.ObjectConfig{
	Name: "Item",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Product": &graphql.Field{
			Type:        graphql.NewNonNull(ProductSchema),
			Description: "Getting the Product",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {

				item, ok := params.Source.(Item)
				if !ok {
					return nil, nil
				}

				DB.First(&item).Related(&item.Product, "Product")
				return item.Product, nil
			},
		},
		"Price": &graphql.Field{
			Type: graphql.Float,
		},
		"Qty": &graphql.Field{
			Type: graphql.Float,
		},
	},
}

ItemConfig is the config for the Item object

ItemSchema is the schema for the Item model

View Source
var MutationConfig = graphql.ObjectConfig{
	Name: "RootMutation",
	Fields: graphql.Fields{

		"CreateUser": CreateUser,

		"UpdateUser": UpdateUser,

		"CreateTag": CreateTag,

		"UpdateTag": UpdateTag,

		"CreateProduct": CreateProduct,

		"UpdateProduct": UpdateProduct,

		"ProductReview": ProductReview,

		"CreateCategory": CreateCategory,

		"UpdateCategory": UpdateCategory,

		"CreateOrder": CreateOrder,

		"UpdateOrder": UpdateOrder,

		"CreateItem": CreateItem,

		"UpdateItem": UpdateItem,

		"CreateCart": CreateCart,

		"UpdateCart": UpdateCart,
	},
}

MutationConfig for the graphql server mutation

View Source
var OrderConfig = graphql.ObjectConfig{
	Name: "Order",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Name": &graphql.Field{
			Type: graphql.String,
		},
		"Items": &graphql.Field{
			Type:        graphql.NewList(ItemSchema),
			Description: "Getting the list of items",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {

				order, ok := params.Source.(Order)
				if !ok {
					return nil, nil
				}

				DB.First(&order).Related(&order.Items, "Items")
				return order.Items, nil
			},
		},
		"Total": &graphql.Field{
			Type: graphql.Float,
		},
		"Date": &graphql.Field{
			Type: graphql.DateTime,
		},
	},
}

OrderConfig is the config for the Order object

OrderSchema is the schema of the Order model

View Source
var ProductArgumentConfig = graphql.FieldConfigArgument{
	"Name": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.String),
	},
	"Brand": &graphql.ArgumentConfig{
		Type: graphql.String,
	},
	"Description": &graphql.ArgumentConfig{
		Type: graphql.String,
	},
	"Tags": &graphql.ArgumentConfig{
		Type: graphql.NewList(graphql.Int),
	},
	"Price": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Float),
	},
	"Image": &graphql.ArgumentConfig{
		Type: graphql.String,
	},
}

ProductArgumentConfig is argument config required for the product

View Source
var ProductConfig = graphql.ObjectConfig{
	Name: "Product",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Name": &graphql.Field{
			Type: graphql.String,
		},
		"Brand": &graphql.Field{
			Type: graphql.String,
		},
		"Description": &graphql.Field{
			Type: graphql.String,
		},
		"Tags": &graphql.Field{
			Type: graphql.NewList(TagSchema),
		},
		"Price": &graphql.Field{
			Type: graphql.Float,
		},
		"Image": &graphql.Field{
			Type: graphql.String,
		},
		"Reviews": &graphql.Field{
			Type: graphql.NewList(ReviewSchema),
		},
	},
}

ProductConfig is the config for the product object

View Source
var ProductReview = &graphql.Field{
	Type:        ProductSchema,
	Description: "Update existing Product",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
		"Review": &graphql.ArgumentConfig{
			Type: graphql.String,
		},
		"Rating": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
		"ReviewID": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
		"Add": &graphql.ArgumentConfig{
			Type: graphql.Boolean,
		},
		"Remove": &graphql.ArgumentConfig{
			Type: graphql.Boolean,
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		review, okr := params.Args["Review"]
		rating, okrr := params.Args["Rating"]
		reviewID, okri := params.Args["ReviewID"]
		add, oka := params.Args["Add"]
		remove, okre := params.Args["Remove"]

		product := Product{
			ID: uint(id),
		}
		reviews := []Review{}
		DB.Model(&product).Related(&reviews, "Reviews")
		product.Reviews = reviews

		if okr && okrr && oka {
			ad, ok := add.(bool)
			if ok && ad {
				r := Review{Review: review.(string), Rating: rating.(int)}
				DB.Create(&r)
				product.Reviews = append(product.Reviews, r)
			}
		}
		if okri && okre {
			rm, ok := remove.(bool)
			if rm && ok {
				review := Review{ID: uint(reviewID.(int))}
				for i := len(product.Reviews) - 1; i >= 0; i-- {
					if product.Reviews[i].ID != review.ID {
						continue
					}
					copy(product.Reviews[i:], product.Reviews[i+1:])
					product.Reviews = product.Reviews[:len(product.Reviews)-1]
					DB.Model(&product).Association("Reviews").Delete(&review)
					DB.Delete(&review)
					break
				}
			}
		}
		DB.Save(&product)

		return product, nil
	},
}

ProductReview for adding areview to a Product

ProductSchema is the schema of the product model

View Source
var QueryConfig = graphql.ObjectConfig{
	Name: "RootQuery",
	Fields: graphql.Fields{

		"User": ReadUser,

		"Users": ReadUsers,

		"Review": ReadReview,

		"Tag": ReadTag,

		"Tags": ReadTags,

		"Product": ReadProduct,

		"Category": ReadCategory,

		"Categories": ReadCategories,

		"Order": ReadOrder,

		"Item": ReadItem,

		"Cart": ReadCart,
	},
}

QueryConfig for graphql server query

View Source
var ReadCart = &graphql.Field{
	Type:        CartSchema,
	Description: "Get a single Cart and its detail",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		cart := Cart{ID: uint(id)}

		DB.First(&cart)

		return cart, nil
	},
}

ReadCart will read a Cart given a CartID

View Source
var ReadCategories = &graphql.Field{
	Type:        graphql.NewList(CategorySchema),
	Description: "Get all the categories",
	Resolve:     ReadCategoryResolve,
}

ReadCategories will read all categories

View Source
var ReadCategory = &graphql.Field{
	Type:        CategorySchema,
	Description: "Get a single category",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
	},
	Resolve: ReadCategoryResolve,
}

ReadCategory will read a Category

View Source
var ReadCategoryResolve = func(params graphql.ResolveParams) (interface{}, error) {

	id, ok := params.Args["ID"].(int)
	category := Category{ID: uint(id)}

	if !ok {
		cats := []Category{}
		DB.Find(&cats)
		for i := 0; i < len(cats); i++ {
			DB.First(&cats[i]).Related(&cats[i].Products, "Products").Related(&cats[i].SubCategories, "SubCategories")
		}
		return cats, nil
	}

	DB.First(&category).Related(&category.Products, "Products").Related(&category.SubCategories, "SubCategories")

	return category, nil
}

ReadCategoryResolve is the resolve function for the category read resolve

View Source
var ReadItem = &graphql.Field{
	Type:        ItemSchema,
	Description: "Get a single Item and its detail",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		item := Item{ID: uint(id)}

		DB.First(&item)

		return item, nil
	},
}

ReadItem will read a Item given an ItemID

View Source
var ReadOrder = &graphql.Field{
	Type:        OrderSchema,
	Description: "Get a single Order and its detail",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		order := Order{ID: uint(id)}

		DB.First(&order)

		return order, nil
	},
}

ReadOrder will read a Order given an OrderID

View Source
var ReadProduct = &graphql.Field{
	Type:        ProductSchema,
	Description: "Get a single Product",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		Product := Product{ID: uint(id)}

		DB.First(&Product).Related(&Product.Tags, "Tags").Related(&Product.Reviews, "Reviews")

		return Product, nil
	},
}

ReadProduct will read a Product

View Source
var ReadReview = &graphql.Field{
	Type:        ReviewSchema,
	Description: "Get a single review",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, ok := params.Args["ID"]
		review := Review{}

		if !ok {

			return review, nil
		}

		DB.First(&review, uint(id.(int)))

		return review, nil
	},
}

ReadReview will read a review

View Source
var ReadTag = &graphql.Field{
	Type:        TagSchema,
	Description: "Get a single Tag",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
	},
	Resolve: ReadTagResolve,
}

ReadTag will read a Tag

View Source
var ReadTagResolve = func(params graphql.ResolveParams) (interface{}, error) {

	id, ok := params.Args["ID"]
	tag := Tag{}

	if !ok {
		//id is not given
		var tags []Tag
		DB.Find(&tags)
		return tags, nil
	}

	DB.First(&tag, uint(id.(int)))

	return tag, nil
}

ReadTagResolve is the resolve function for both read tag/tags

View Source
var ReadTags = &graphql.Field{
	Type:        graphql.NewList(TagSchema),
	Description: "Get a single Tag",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
	},
	Resolve: ReadTagResolve,
}

ReadTags will read a Tag

View Source
var ReadUser = &graphql.Field{
	Type:        UserSchema,
	Description: "Get a single user",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
	},
	Resolve: ReadUserResolve,
}

ReadUser will read a user

View Source
var ReadUserResolve = func(params graphql.ResolveParams) (interface{}, error) {

	id, ok := params.Args["ID"].(int)
	user := User{ID: uint(id)}

	if !ok {

		users := []User{}

		DB.Find(&users)
		return users, nil
	}

	DB.First(&user)

	return user, nil
}

ReadUserResolve is the resolve function for user and list of users

View Source
var ReadUsers = &graphql.Field{
	Type:        graphql.NewList(UserSchema),
	Description: "Get all users",
	Resolve:     ReadUserResolve,
}

ReadUsers will read a user

View Source
var ReviewConfig = graphql.ObjectConfig{
	Name: "Review",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Review": &graphql.Field{
			Type: graphql.String,
		},
		"Rating": &graphql.Field{
			Type: graphql.Int,
		},
	},
}

ReviewConfig is the object config for review interface

ReviewSchema is the schema of the review model

Schema is the graphql schema

View Source
var TagConfig = graphql.ObjectConfig{
	Name: "Tag",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Name": &graphql.Field{
			Type: graphql.String,
		},
	},
}

TagConfig is the object config for tag

TagSchema is the schema of the Tag model

View Source
var UpdateCart = &graphql.Field{
	Type:        CartSchema,
	Description: "Update existing Cart",
	Args:        UpdateCartArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		total, okt := params.Args["Total"]
		addItem, okai := params.Args["AddItem"]
		removeItem, okri := params.Args["RemoveItem"]

		cart := Cart{ID: uint(id)}

		if okt {
			cart.Total = total.(float32)
		}

		items := []Item{}
		DB.Model(&cart).Related(&items, "Items")
		cart.Items = items

		if okai {
			i := Item{ID: uint(addItem.(int))}
			DB.First(&i)
			cart.Items = append(cart.Items, i)
		}

		if okri {
			item := Item{ID: uint(removeItem.(int))}
			for i := len(cart.Items) - 1; i >= 0; i++ {
				if cart.Items[i].ID != item.ID {
					continue
				}
				copy(cart.Items[i:], cart.Items[i+1:])
				cart.Items = cart.Items[:len(cart.Items)-1]
				DB.Model(&cart).Association("Items").Delete(&item)
				break
			}
		}

		DB.Save(&cart)

		return cart, nil
	},
}

UpdateCart is for updating an Order

View Source
var UpdateCartArgumentConfig = graphql.FieldConfigArgument{
	"ID": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Int),
	},
	"Total": &graphql.ArgumentConfig{
		Type: graphql.Float,
	},
	"AddItem": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
	"RemoveItem": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
}

UpdateCartArgumentConfig is argument config required update of the Order

View Source
var UpdateCategory = &graphql.Field{
	Type:        CategorySchema,
	Description: "Update existing Category",
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		name, okn := params.Args["Name"]
		description, okd := params.Args["Description"]
		addCategory, okas := params.Args["AddSubCategory"]
		removeCategory, okrs := params.Args["RemoveSubCategory"]
		addProduct, okap := params.Args["AddProduct"]
		removeProduct, okrp := params.Args["RemoveProduct"]

		category := Category{
			ID: uint(id),
		}
		DB.First(&category)
		DB.Model(&category).Related(&category.SubCategories, "SubCategories").Related(&category.Products, "Products")

		if okn {
			category.Name = name.(string)
		}
		if okd {
			category.Description = description.(string)
		}
		if okas {
			sc := Category{ID: uint(addCategory.(int))}
			DB.First(&sc)
			if len(sc.Name) != 0 {
				category.SubCategories = append(category.SubCategories, sc)
			}
		}
		if okrs {
			sc := Category{ID: uint(removeCategory.(int))}
			for i := len(category.SubCategories) - 1; i >= 0; i-- {
				if category.SubCategories[i].ID != sc.ID {
					continue
				}
				copy(category.SubCategories[i:], category.SubCategories[i+1:])
				category.SubCategories = category.SubCategories[:len(category.SubCategories)-1]
				DB.Model(&category).Association("SubCategories").Delete(&sc)
				break
			}
		}
		if okap {
			p := Product{ID: uint(addProduct.(int))}
			DB.First(&p)
			if len(p.Name) != 0 {
				category.Products = append(category.Products, p)
			}
		}
		if okrp {
			p := Product{ID: uint(removeProduct.(int))}
			for i := len(category.Products) - 1; i >= 0; i-- {
				if category.Products[i].ID != p.ID {
					continue
				}
				copy(category.Products[i:], category.Products[i+1:])
				category.Products = category.Products[:len(category.Products)-1]
				DB.Model(&category).Association("Products").Delete(&p)
				break
			}
		}
		DB.Save(&category)

		return category, nil
	},
}

UpdateCategory for creating a Category

View Source
var UpdateItem = &graphql.Field{
	Type:        ItemSchema,
	Description: "Update an Item",
	Args:        UpdateItemArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		price, okp := params.Args["Price"]
		qty, okq := params.Args["Qty"]
		changeProduct, okcp := params.Args["ChangeProduct"]

		item := Item{ID: uint(id)}

		if okp {
			item.Price = price.(float64)
		}
		if okq {
			item.Qty = qty.(int)
		}

		DB.First(&item).Related(&item.Product, "Product")

		if okcp {

			pdt := Product{}
			DB.Where(changeProduct.(int)).Find(&pdt)
			DB.Model(&item).Association("Product").Delete(&item.Product)
			item.Product = pdt
		}

		DB.Save(&item)

		return item, nil
	},
}

UpdateItem for updating an Item

View Source
var UpdateItemArgumentConfig = graphql.FieldConfigArgument{
	"ID": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Int),
	},
	"Price": &graphql.ArgumentConfig{
		Type: graphql.Float,
	},
	"Qty": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
	"ChangeProduct": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
}

UpdateItemArgumentConfig is argument config required for the Item

View Source
var UpdateOrder = &graphql.Field{
	Type:        OrderSchema,
	Description: "Update existing Order",
	Args:        UpdateOrderArgumentConfig,
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		name, okn := params.Args["Name"]
		total, okt := params.Args["Total"]
		date, _ := params.Args["Date"]
		addItem, okai := params.Args["AddItem"]
		removeItem, okri := params.Args["RemoveItem"]

		order := Order{
			ID:   uint(id),
			Date: date.(time.Time),
		}

		if okn {
			order.Name = name.(string)
		}
		if okt {
			order.Total = total.(float64)
		}

		items := []Item{}
		DB.Model(&order).Related(&items, "Items")
		order.Items = items

		if okai {
			i := Item{ID: uint(addItem.(int))}
			DB.First(&i)
			order.Items = append(order.Items, i)
		}

		if okri {
			item := Item{ID: uint(removeItem.(int))}
			for i := len(order.Items) - 1; i >= 0; i++ {
				if order.Items[i].ID != item.ID {
					continue
				}
				copy(order.Items[i:], order.Items[i+1:])
				order.Items = order.Items[:len(order.Items)-1]
				DB.Model(&order).Association("Items").Delete(&item)
				break
			}
		}

		DB.Save(&order)

		return order, nil
	},
}

UpdateOrder is for updating an Order

View Source
var UpdateOrderArgumentConfig = graphql.FieldConfigArgument{
	"ID": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.Int),
	},
	"Name": &graphql.ArgumentConfig{
		Type: graphql.String,
	},
	"Total": &graphql.ArgumentConfig{
		Type: graphql.Float,
	},
	"Date": &graphql.ArgumentConfig{
		Type: graphql.NewNonNull(graphql.DateTime),
	},
	"AddItem": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
	"RemoveItem": &graphql.ArgumentConfig{
		Type: graphql.Int,
	},
}

UpdateOrderArgumentConfig is argument config required update of the Order

View Source
var UpdateProduct = &graphql.Field{
	Type:        ProductSchema,
	Description: "Update existing Product",
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		name, okn := params.Args["Name"]
		brand, okb := params.Args["Brand"]
		description, okd := params.Args["Description"]
		addTag, okat := params.Args["AddTag"]
		removeTag, okrt := params.Args["RemoveTag"]
		price, okp := params.Args["Price"]
		image, oki := params.Args["Image"]

		product := Product{
			ID: uint(id),
		}
		tags := []Tag{}
		DB.Model(&product).Related(&tags, "Tags")
		product.Tags = tags

		if okn {
			product.Name = name.(string)
		}
		if okb {
			product.Brand = brand.(string)
		}
		if okd {
			product.Description = description.(string)
		}
		if okat {
			t := Tag{ID: uint(addTag.(int))}
			DB.First(&t)
			if len(t.Name) != 0 {
				product.Tags = append(product.Tags, t)
			}
		}
		if okrt {
			tag := Tag{ID: uint(removeTag.(int))}
			for i := len(product.Tags) - 1; i >= 0; i-- {
				if product.Tags[i].ID != tag.ID {
					continue
				}
				copy(product.Tags[i:], product.Tags[i+1:])
				product.Tags = product.Tags[:len(product.Tags)-1]
				DB.Model(&product).Association("Tags").Delete(&tag)
				break
			}
		}
		if okp {
			product.Price = price.(float64)
		}
		if oki {
			product.Image = image.(string)
		}
		DB.Save(&product)

		return product, nil
	},
}

UpdateProduct for updating a Product

View Source
var UpdateTag = &graphql.Field{
	Type:        TagSchema,
	Description: "Update existing Tag",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
		"Name": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		name, _ := params.Args["Name"].(string)

		tag := Tag{
			ID:   uint(id),
			Name: name,
		}
		DB.Update(&tag)

		return tag, nil
	},
}

UpdateTag for creating a Tag

View Source
var UpdateUser = &graphql.Field{
	Type:        UserSchema,
	Description: "Update existing user",
	Args: graphql.FieldConfigArgument{
		"ID": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.Int),
		},
		"Number": &graphql.ArgumentConfig{
			Type: graphql.String,
		},
		"Password": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
		"Name": &graphql.ArgumentConfig{
			Type: graphql.NewNonNull(graphql.String),
		},
		"AddOrder": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
		"RemoveOrder": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
		"AddCart": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
		"RemoveCart": &graphql.ArgumentConfig{
			Type: graphql.Int,
		},
	},
	Resolve: func(params graphql.ResolveParams) (interface{}, error) {

		id, _ := params.Args["ID"].(int)
		number, okn := params.Args["Number"]
		password, _ := params.Args["Password"].(string)
		name, _ := params.Args["Name"].(string)
		addOrder, okao := params.Args["AddOrder"]
		removeOrder, okro := params.Args["RemoveOrder"]
		addCart, okac := params.Args["AddCart"]
		removeCart, okrc := params.Args["RemoveCart"]

		user := User{
			ID:       uint(id),
			Password: password,
			Name:     name,
		}

		if okn {
			user.Number = number.(string)
		}

		orders := []Order{}
		DB.Model(&user).Related(&orders, "Orders")
		user.Orders = orders

		if okao {
			o := Order{ID: uint(addOrder.(int))}
			DB.First(&o)
			user.Orders = append(user.Orders, o)
		}

		if okro {
			o := Order{ID: uint(removeOrder.(int))}
			for i := len(user.Orders) - 1; i >= 0; i++ {
				if user.Orders[i].ID != o.ID {
					continue
				}
				copy(user.Orders[i:], user.Orders[i+1:])
				user.Orders = user.Orders[:len(user.Orders)-1]
				DB.Model(&user).Association("Orders").Delete(&o)
				break
			}
		}

		if okac {
			c := Cart{ID: uint(addCart.(int))}
			DB.First(&c)
			user.Cart = c
		}

		if okrc {
			cart := Cart{}
			DB.Where(removeCart.(int)).Find(&cart)
			DB.Model(&user).Association("Cart").Delete(&user.Cart)
			user.Cart = Cart{}
		}

		DB.Save(&user)

		return user, nil
	},
}

UpdateUser for updating a user

View Source
var UserConfig = graphql.ObjectConfig{
	Name: "User",
	Fields: graphql.Fields{
		"ID": &graphql.Field{
			Type: graphql.Int,
		},
		"Number": &graphql.Field{
			Type: graphql.String,
		},
		"Password": &graphql.Field{
			Type: graphql.String,
		},
		"Name": &graphql.Field{
			Type: graphql.String,
		},
		"Cart": &graphql.Field{
			Type:        CartSchema,
			Description: "Getting the cart",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {

				user, ok := params.Source.(User)
				if !ok {
					return nil, nil
				}

				DB.First(&user).Related(&user.Cart, "Cart")
				return user.Cart, nil
			},
		},
		"Orders": &graphql.Field{
			Type:        graphql.NewList(OrderSchema),
			Description: "Getting the Order",
			Resolve: func(params graphql.ResolveParams) (interface{}, error) {

				user, ok := params.Source.(User)
				if !ok {
					return nil, nil
				}

				DB.Find(&user).Related(&user.Orders, "Orders")
				fmt.Println(user.Orders)
				return user.Orders, nil
			},
		},
	},
}

UserConfig is the object config for user

UserSchema is the schema of the user model

Functions

func InitCategories

func InitCategories()

InitCategories will do the required initalizations for the category model to work with graphql

func InitProduct

func InitProduct()

InitProduct will do the initializations required for the product

Types

type Cart

type Cart struct {
	ID     uint    `gorm:"primary_key"`
	Items  []Item  `gorm:"foreign_key:CartID"` //Items is the list of items in the cart
	Total  float32 //Total price of items in the cart
	UserID uint
}

Cart is the cart for shopping

type Category

type Category struct {
	//ID of the product
	ID          uint   `gorm:"primary_key"`
	Name        string //Name of the category
	Description string //Description is the description for the category
	//SubCategories for further classification
	SubCategories []Category `gorm:"many2many:category_subcategories;association_jointable_foreignkey:subcategory_id"`
	//Products has the list of products in a category
	Products []Product `gorm:"many2many:category_products;"`
}

Category helps to classify the products. It can have subcategories too

type Item

type Item struct {
	ID      uint    `gorm:"primary_key"`
	Product Product `gorm:"foreign_key:ItemID"` //Product the item represents
	Price   float64 //Price is the price of a single item
	Qty     int     //Qty is the number of items purchased
	OrderID uint    //This is the foreign_key for Order.Items
	CartID  uint    //This is the foreign_key for Cart.Items
}

Item is the basic unit in the cart the identifies a product with price and qty

type Order

type Order struct {
	ID     uint      `gorm:"primary_key"`
	Name   string    //The Order name to be displayed in the frontend
	Items  []Item    `gorm:"foreign_key:OrderID"` //Items is the list of items in the cart
	Total  float64   //Total price of items in the cart
	Date   time.Time //Date on which the order was made
	UserID uint
}

Order made by the user

type Product

type Product struct {
	//ID of the product
	ID          uint   `gorm:"primary_key"`
	Name        string //Name of the product
	Brand       string //Brand to which the product belongs to
	Description string //Description of the product
	//Tags is the tags associated with the product
	Tags  []Tag   `gorm:"many2many:product_tags;"`
	Price float64 //Price of the product
	Image string  //Image url of the product
	//Reviews given to this product
	Reviews []Review `gorm:"many2many:product_reviews;"`
	ItemID  uint     // foreign_key for Item.Product
}

Product is the data structure of the product

type Review

type Review struct {
	//ID of the review
	ID uint `gorm:"primary_key"`
	//Review of the user
	Review string
	//Rating given by the user
	Rating int
}

Review given by a user for the product

type Tag

type Tag struct {
	//ID of the Tag
	ID uint `gorm:"primary_key"`
	//Name of the tag
	Name string
}

Tag is tag to for indexing purpose

type User

type User struct {
	ID       uint    `gorm:"primary_key"` //ID of the user
	Number   string  //Number is the mobile number of the user
	Password string  //Password is the password the user
	Name     string  //Name is the display name of the user
	Cart     Cart    `gorm:"foreign_key:UserID"` //This is the current cart of the user
	Orders   []Order `gorm:"foreign_key:UserID"` //Orders given by this user
}

User is the model of the user

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL