Esempio n. 1
0
func (ct *Categories) Get() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		slug := c.Param("slug")
		collection := ct.Connection.Collection("Category")
		result := &models.Category{}

		err := collection.FindOne(bson.M{"slug": slug}, result)

		if err == nil {
			var parent *models.Category
			// get parent if available
			if result.Parent != "" {
				parent = &models.Category{}
				collection.FindOne(bson.M{"slug": result.Parent}, parent)
			}
			// cast category type to category with parent type
			category := models.ConvertCategory(result, parent)
			c.JSON(http.StatusOK, category)
		} else if _, ok := err.(*bongo.DocumentNotFoundError); ok {
			c.AbortWithStatus(http.StatusNotFound)
		} else {
			panic(err)
		}
	})
}
Esempio n. 2
0
func (ct *Categories) List() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		dbResult := ct.Connection.Collection("Category").Find(bson.M{})

		category := &models.Category{}
		var categories []models.Category

		for dbResult.Next(category) {
			categories = append(categories, *category)
		}

		c.JSON(http.StatusOK, categories)
	})
}
Esempio n. 3
0
func (ct *Categories) GetTree() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		dbResult := ct.Connection.Collection("Category").Find(bson.M{})

		category := &models.Category{}

		lookup := make(map[string]*models.CategoryNode)
		var roots []*models.CategoryNode

		// iterate results from db
		for dbResult.Next(category) {
			// build tree
			// create CategoryNode
			var node *models.CategoryNode
			if n, ok := lookup[category.Slug]; ok {
				// complete half instantiated node(created below)
				node = n
				node.Icon = category.Icon
				node.Name = category.Name
			} else {
				// create node and add to lookup table
				node = &models.CategoryNode{
					Slug: category.Slug,
					Icon: category.Icon,
					Name: category.Name,
				}
				lookup[category.Slug] = node
			}

			if category.Parent == "" { // is root
				roots = append(roots, node)
			} else { // is child
				parent, found := lookup[category.Parent]
				// create empty parent and add to lookup
				if !found {
					parent = &models.CategoryNode{}
					lookup[category.Parent] = parent
				}
				parent.Children = append(parent.Children, node)
			}
		}

		c.JSON(http.StatusOK, roots)
	})
}
Esempio n. 4
0
File: api.go Progetto: quid-city/api
// MethodNotAllowed sends 405 status with no response body
func MethodNotAllowed() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		c.AbortWithStatus(http.StatusMethodNotAllowed)
	})
}