func GetCollectors(c *middleware.Context, query m.GetCollectorsQuery) Response { query.OrgId = c.OrgId if err := bus.Dispatch(&query); err != nil { return ApiError(500, "Failed to query collectors", err) } return Json(200, query.Result) }
func GetCollectors(query *m.GetCollectorsQuery) error { sess := x.Table("collector") rawParams := make([]interface{}, 0) rawSql := `SELECT GROUP_CONCAT(DISTINCT(collector_tag.tag)) as tags, collector.* FROM collector LEFT JOIN collector_tag ON collector.id = collector_tag.collector_id AND collector_tag.org_id=? ` rawParams = append(rawParams, query.OrgId) whereSql := make([]string, 0) whereSql = append(whereSql, "(collector.public=1 OR collector.org_id=?)") rawParams = append(rawParams, query.OrgId) if len(query.Tag) > 0 { // this is a bit complicated because we want to // match only collectors that have the tag(s), // but we still need to return all of the tags that // the collector has. rawSql += `LEFT JOIN collector_tag AS lt ON lt.collector_id = collector.id AND collector_tag.org_id=? ` rawParams = append(rawParams, query.OrgId) p := make([]string, len(query.Tag)) for i, t := range query.Tag { p[i] = "?" rawParams = append(rawParams, t) } whereSql = append(whereSql, fmt.Sprintf("lt.tag IN (%s)", strings.Join(p, ","))) } if len(query.Name) > 0 { p := make([]string, len(query.Name)) for i, t := range query.Name { p[i] = "?" rawParams = append(rawParams, t) } whereSql = append(whereSql, fmt.Sprintf("collector.name IN (%s)", strings.Join(p, ","))) } if query.Public != "" { if p, err := strconv.ParseBool(query.Public); err == nil { whereSql = append(whereSql, "collector.public=?") rawParams = append(rawParams, p) } else { return err } } rawSql += "WHERE " + strings.Join(whereSql, " AND ") rawSql += " GROUP BY collector.id" result := make([]CollectorWithTag, 0) err := sess.Sql(rawSql, rawParams...).Find(&result) if err != nil { return err } collectors := make([]*m.CollectorDTO, len(result)) //iterate through all of the results and build out our collectors model. for i, row := range result { tags := make([]string, 0) if row.Tags != "" { tags = strings.Split(row.Tags, ",") } collectors[i] = &m.CollectorDTO{ Id: row.Id, OrgId: row.OrgId, Name: row.Name, Slug: row.Slug, Latitude: row.Latitude, Longitude: row.Longitude, Tags: tags, Public: row.Public, Online: row.Online, Enabled: row.Enabled, } } query.Result = collectors return nil }