当前位置: 首页>>代码示例>>Golang>>正文


Golang services.DB类代码示例

本文整理汇总了Golang中github.com/ownode/services.DB的典型用法代码示例。如果您正苦于以下问题:Golang DB类的具体用法?Golang DB怎么用?Golang DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Get

// get a service
func (c *ServiceController) Get(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	service, found, err := models.FindServiceByObjectID(db.GetPostgresHandle(), params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "service was not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	respObj, _ := services.StructToJsonToMap(service)
	services.Res(res).Json(respObj)
}
开发者ID:ownode,项目名称:ownode,代码行数:16,代码来源:service.go

示例2: Get

// get an identity
func (c *IdentityController) Get(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	identity, found, err := models.FindIdentityByObjectID(db.GetPostgresHandle(), params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "identity was not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// create response
	respObj, _ := services.StructToJsonToMap(identity)

	if identity.Issuer {
		respObj["soul_balance"] = identity.SoulBalance
	}

	services.Res(res).Json(respObj)
}
开发者ID:ownode,项目名称:ownode,代码行数:22,代码来源:identity.go

示例3: Open

// open/unlock a wallet
func (c *WalletController) Open(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get wallet
	wallet, found, err := models.FindWalletByObjectID(dbTx, params["id"])
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "wallet not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure wallet matches authorizing wallet
	if wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "client does not have permission to access wallet")
		return
	}

	// update lock state to false
	wallet.Lock = false

	// save and commit
	dbTx.Save(&wallet).Commit()
	services.Res(res).Json(wallet)
}
开发者ID:ownode,项目名称:ownode,代码行数:41,代码来源:wallet.go

示例4: Lock

// lock sets set the 'open' property of an object to false. Also resets all fields used by
// all open methods
func (c *ObjectController) Lock(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get the object
	object, found, err := models.FindObjectByObjectID(dbTx, params["id"])
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "object was not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure object belongs to authorizing wallet
	if object.Wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "objects: object does not belong to authorizing wallet")
		return
	}

	// clear open related fields of object
	clearOpen(&object)

	// save update and commit
	dbTx.Save(&object).Commit()
	services.Res(res).Json(object)
}
开发者ID:ownode,项目名称:ownode,代码行数:42,代码来源:object.go

示例5: Get

// get an object by its id or pin
func (c *ObjectController) Get(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	dbObj := db.GetPostgresHandle()
	object, found, err := models.FindObjectByObjectIDOrPin(dbObj, params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "object was not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// construct response. remove private fields
	respObj, _ := services.StructToJsonToMap(object)
	delete(respObj["wallet"].(map[string]interface{})["identity"].(map[string]interface{}), "soul_balance")
	delete(respObj["wallet"].(map[string]interface{})["identity"].(map[string]interface{}), "email")
	delete(respObj["service"].(map[string]interface{})["identity"].(map[string]interface{}), "soul_balance")
	delete(respObj["service"].(map[string]interface{})["identity"].(map[string]interface{}), "email")

	services.Res(res).Json(respObj)
}
开发者ID:ownode,项目名称:ownode,代码行数:23,代码来源:object.go

示例6: PostgresAutoMigration

func PostgresAutoMigration(db *services.DB) {
	db.GetPostgresHandle().AutoMigrate(&models.Token{}, &models.Service{}, &models.Identity{}, &models.Wallet{}, &models.Object{})
	services.Println("Migration complete!")
}
开发者ID:ownode,项目名称:ownode,代码行数:4,代码来源:migration.go

示例7: Create

// create an identity
func (c *IdentityController) Create(res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// parse request body
	var body identityCreateBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// full name is required
	if validator.IsNull(body.FullName) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: full_name")
		return
	}

	// email is required
	if validator.IsNull(body.Email) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: email")
		return
	}

	// email is required
	if !validator.IsEmail(body.Email) {
		services.Res(res).Error(400, "invalid_email", "email is invalid")
		return
	}

	// create identity
	newIdentity := models.Identity{
		ObjectID: bson.NewObjectId().Hex(),
		FullName: body.FullName,
		Email:    body.Email,
	}

	// if request is from Issuer controller, set issuer field to true
	if d := req.GetData("isIssuer"); d != nil && d.(bool) {

		// object is required
		if validator.IsNull(body.ObjectName) {
			services.Res(res).Error(400, "missing_parameter", "Missing required field: object_name")
			return
		}

		// base currency is required
		if validator.IsNull(body.BaseCurrency) {
			services.Res(res).Error(400, "missing_parameter", "Missing required field: base_currency")
			return
		}

		// base currency must be supported
		if !services.StringInStringSlice(config.SupportedBaseCurrencies, body.BaseCurrency) {
			services.Res(res).Error(400, "invalid_base_currency", "base currency is unknown")
			return
		}

		newIdentity.Issuer = true
		newIdentity.ObjectName = body.ObjectName
		newIdentity.BaseCurrency = body.BaseCurrency
	}

	err := models.CreateIdentity(db.GetPostgresHandle(), &newIdentity)
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// create response
	respObj, _ := services.StructToJsonToMap(newIdentity)

	if newIdentity.Issuer {
		respObj["soul_balance"] = newIdentity.SoulBalance
	}

	services.Res(res).Json(respObj)

}
开发者ID:ownode,项目名称:ownode,代码行数:78,代码来源:identity.go

示例8: RenewSoul

// renew an issuer identity soul
func (c *IdentityController) RenewSoul(res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// parse request body
	var body soulRenewBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// identity id is required
	if validator.IsNull(body.IdentityId) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: identity_id")
		return
	}

	// soul balance is required
	if body.SoulBalance == 0 {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: soul_balance")
		return
	}

	// soul balance must be greater than zero
	if body.SoulBalance < MinimumObjectUnit {
		services.Res(res).Error(400, "invalid_soul_balance", "Soul balance must be equal or greater than minimum object unit which is 0.00000001")
		return
	}

	// ensure identity exists
	identity, found, err := models.FindIdentityByObjectID(db.GetPostgresHandle(), body.IdentityId)
	if !found {
		services.Res(res).Error(404, "invalid_identity", "identity_id is unknown")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure identity is an issuer
	if !identity.Issuer {
		services.Res(res).Error(400, "invalid_identity", "identity is not an issuer")
		return
	}

	// add to soul balance
	newIdentity, err := models.AddToSoulByObjectID(db.GetPostgresHandle(), identity.ObjectID, body.SoulBalance)
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// create response, hide some fields
	respObj, _ := services.StructToJsonToMap(newIdentity)

	if newIdentity.Issuer {
		respObj["soul_balance"] = newIdentity.SoulBalance
	}

	services.Res(res).Json(respObj)
}
开发者ID:ownode,项目名称:ownode,代码行数:62,代码来源:identity.go

示例9: Create

// create a service
func (c *ServiceController) Create(res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// parse request body
	var body createBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_client", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// name is required
	if c.validate.IsEmpty(body.FullName) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: full_name")
		return
	}

	// full name must have max of 60 characters
	if !validator.StringLength(body.FullName, "1", "60") {
		services.Res(res).Error(400, "invalid_full_name", "full_name character limit is 60")
		return
	}

	// service name is required
	if c.validate.IsEmpty(body.ServiceName) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: service_name")
		return
	}

	// service name must have max of 30 characters
	if !validator.StringLength(body.ServiceName, "1", "60") {
		services.Res(res).Error(400, "invalid_service_name", "service_name character limit is 60")
		return
	}

	// description is required
	if c.validate.IsEmpty(body.Description) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: description")
		return
	}

	// description must have max of 140 characters
	if !validator.StringLength(body.Description, "1", "140") {
		services.Res(res).Error(400, "invalid_description", "description character limit is 140")
		return
	}

	// email is required
	if c.validate.IsEmpty(body.Email) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: email")
		return
	}

	// email must be valid
	if !validator.IsEmail(body.Email) {
		services.Res(res).Error(400, "invalid_email", "email is invalid")
		return
	}

	// create identity
	newIdentity := &models.Identity{
		ObjectID: bson.NewObjectId().Hex(),
		FullName: body.FullName,
		Email:    body.Email,
	}

	// start db transaction
	dbTx := db.GetPostgresHandle().Begin()

	if err := models.CreateIdentity(dbTx, newIdentity); err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// create client credentials
	clientId := services.GetRandString(services.GetRandNumRange(32, 42))
	clientSecret := services.GetRandString(services.GetRandNumRange(32, 42))

	// create new service object
	newService := models.Service{
		ObjectID:     bson.NewObjectId().Hex(),
		Name:         body.ServiceName,
		Description:  body.Description,
		ClientID:     clientId,
		ClientSecret: clientSecret,
		Identity:     newIdentity,
	}

	// create service
	err := models.CreateService(dbTx, &newService)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// commit db transaction
	dbTx.Commit()
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:service.go

示例10: List

// list object
// supports
// - pagination using 'page' query. Use per_page to set the number of results per page. max is 100
// - filters: filter_type, filter_service, filter_open, filter_open_method, filter_gte_date_created
//   filter_lte_date_created
// - sorting: sort_balance, sort_date_created
func (c *WalletController) List(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	dbCon := db.GetPostgresHandle()

	// get wallet
	wallet, found, err := models.FindWalletByObjectID(dbCon, params["id"])
	if !found {
		services.Res(res).Error(404, "not_found", "wallet not found")
		return
	} else if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure wallet matches authorizing wallet
	if wallet.ObjectID != authWalletID {
		services.Res(res).Error(401, "unauthorized", "client does not have permission to access wallet")
		return
	}

	query := req.URL.Query()
	qPage := query.Get("page")
	if c.validate.IsEmpty(qPage) {
		qPage = "0"
	} else if !validator.IsNumeric(qPage) {
		services.Res(res).Error(400, "invalid_parameter", "page query value must be numeric")
		return
	}

	q := make(map[string]interface{})
	q["wallet_id"] = wallet.ID
	order := "id asc"
	limitPerPage := int64(2)
	offset := int64(0)
	currentPage, err := strconv.ParseInt(qPage, 0, 64)
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// set limit per page if provided in query
	qPerPage := query.Get("per_page")
	if !c.validate.IsEmpty(qPerPage) {
		if validator.IsNumeric(qPerPage) {
			qPerPage, _ := strconv.ParseInt(qPerPage, 0, 64)
			if qPerPage > 100 {
				qPerPage = 100
			} else if qPerPage <= 0 {
				qPerPage = limitPerPage
			}
			limitPerPage = qPerPage
		}
	}

	// set current page default and calculate offset
	if currentPage <= 1 {
		currentPage = 1
		offset = 0
	} else {
		offset = (int64(limitPerPage) * currentPage) - int64(limitPerPage)
	}

	// apply type filter if included in query
	filterType := query.Get("filter_type")
	if !c.validate.IsEmpty(filterType) && services.StringInStringSlice([]string{"obj_value", "obj_valueless"}, filterType) {
		q["type"] = filterType
	}

	// apply service filter if included in query
	filterService := query.Get("filter_service")
	if !c.validate.IsEmpty(filterService) {

		// find service
		service, found, err := models.FindServiceByObjectID(db.GetPostgresHandle(), filterService)
		if err != nil {
			c.log.Error(err.Error())
			services.Res(res).Error(500, "", "server error")
			return
		}

		if found {
			q["service_id"] = service.ID
		}
	}

	// apply open filter if included in query
	filterOpen := query.Get("filter_open")
	if !c.validate.IsEmpty(filterOpen) && services.StringInStringSlice([]string{"true", "false"}, filterOpen) {
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:wallet.go

示例11: Charge

// charge an object. Deduct from an object, create one or more objects and
// associated to one or more wallets
func (c *ObjectController) Charge(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// parse body
	var body objectChargeBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// TODO: get client id from access token
	clientID := "kl14zFDq4SHlmmmVNHgLtE0LqCo8BTjyShOH"

	// get db transaction object
	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get service
	service, _, _ := models.FindServiceByClientId(dbTx, clientID)

	// ensure object ids is not empty
	if len(body.IDS) == 0 {
		services.Res(res).ErrParam("ids").Error(400, "invalid_parameter", "provide one or more object ids to charge")
		return
	}

	// ensure object ids length is less than 100
	if len(body.IDS) > 100 {
		services.Res(res).ErrParam("ids").Error(400, "invalid_parameter", "only a maximum of 100 objects can be charge at a time")
		return
	}

	// ensure destination wallet is provided
	if c.validate.IsEmpty(body.DestinationWalletID) {
		services.Res(res).ErrParam("wallet_id").Error(400, "invalid_parameter", "destination wallet id is reqired")
		return
	}

	// ensure amount is provided
	if body.Amount < MinimumObjectUnit {
		services.Res(res).ErrParam("amount").Error(400, "invalid_parameter", fmt.Sprintf("amount is below the minimum charge limit. Mininum charge limit is %.8f", MinimumObjectUnit))
		return
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		services.Res(res).ErrParam("meta").Error(400, "invalid_parameter", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	}

	// ensure destination wallet exists
	wallet, found, err := models.FindWalletByObjectID(dbTx, body.DestinationWalletID)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "api_error")
		return
	} else if !found {
		dbTx.Rollback()
		services.Res(res).ErrParam("wallet_id").Error(404, "not_found", "wallet_id not found")
		return
	}

	// find all objects
	objectsFound, err := models.FindAllObjectsByObjectID(dbTx, body.IDS)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "api_error", "api_error")
		return
	}

	// ensure all objects exists
	if len(objectsFound) != len(body.IDS) {
		dbTx.Rollback()
		services.Res(res).ErrParam("ids").Error(404, "object_error", "one or more objects do not exist")
		return
	}

	// sort object by balance in descending order
	sort.Sort(services.ByObjectBalance(objectsFound))

	// objects to charge
	objectsToCharge := []models.Object{}

	// validate each object
	// check open status (timed and pin)
	// collect the required objects to sufficiently
	// complete a charge from the list of found objects
	for _, object := range objectsFound {

		// as long as the total balance of objects to be charged is not above charge amount
		// keep setting aside objects to charge from.
		// once we have the required objects to cover charge amount, stop processing other objects
		if TotalBalance(objectsToCharge) < body.Amount {
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:object.go

示例12: Open

// open an object for charge/consumption. An object opened in this method
// will be consumable without restriction
func (c *ObjectController) Open(params martini.Params, res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	// parse body
	var body objectOpenBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// ensure open method is provided
	if c.validate.IsEmpty(body.OpenMethod) {
		services.Res(res).Error(400, "invalid_parameter", "open_method: open method is required")
		return
	}

	// ensure a known open method is provided
	if body.OpenMethod != "open" && body.OpenMethod != "open_timed" && body.OpenMethod != "open_pin" {
		services.Res(res).Error(400, "invalid_parameter", "unknown open type method")
		return
	}

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get the object
	object, found, err := models.FindObjectByObjectID(dbTx, params["id"])
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "object was not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure object belongs to authorizing wallet
	if object.Wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "objects: object does not belong to authorizing wallet")
		return
	}

	// set object's open property to true and open_method to `open`
	clearOpen(&object)
	object.Open = true
	object.OpenMethod = models.ObjectOpenDefault

	// for open_timed,
	// set 'open_time' field to indicate object open window
	if body.OpenMethod == "open_timed" {

		// ensure time field is provided
		if body.Time == 0 {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "time: open window time is required. use unix time")
			return
		}

		// time must be in the future
		now := time.Now().UTC()
		if !now.Before(services.UnixToTime(body.Time).UTC()) {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "time: use a unix time pointing to a period in the future")
			return
		}

		object.OpenMethod = models.ObjectOpenTimed
		object.OpenTime = body.Time
	}

	// for open_pin
	// open pin sets a pin for used by charge API
	if body.OpenMethod == "open_pin" {

		// ensure pin is provided
		if c.validate.IsEmpty(body.Pin) {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "pin: pin is required")
			return
		}

		// pin must be numeric
		if !validator.IsNumeric(body.Pin) {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "pin: pin must contain only numeric characters. e.g 4345")
			return
		}

//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:object.go

示例13: Subtract

// create a new object by subtracting from a source object
func (c *ObjectController) Subtract(res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// TODO: get from access token
	// authorizing wallet id
	authWalletID := "55c679145fe09c74ed000001"

	// parse body
	var body objectSubtractBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// object is required
	if c.validate.IsEmpty(body.Object) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: object")
		return
	}

	// amount to subtract is required
	if body.AmountToSubtract < MinimumObjectUnit {
		services.Res(res).Error(400, "invalid_parameter", "amount: amount must be equal or greater than the minimum object unit which is 0.00000001")
		return
	}

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get the object
	object, found, err := models.FindObjectByObjectID(dbTx, body.Object)
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "object was not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure object is a valuable type
	if object.Type == models.ObjectValueless {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_parameter", "object: object must be a valuabe type (obj_value) ")
		return
	}

	// ensure object belongs to authorizing wallet
	if object.Wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "objects: object does not belong to authorizing wallet")
		return
	}

	// ensure object's balance is sufficient
	if object.Balance < body.AmountToSubtract {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_parameter", "amount: object's balance is insufficient")
		return
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !body.InheritMeta && !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		services.Res(res).Error(400, "invalid_meta_size", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	} else {
		if body.InheritMeta {
			body.Meta = object.Meta
		}
	}

	// subtract and update object's balance
	object.Balance = object.Balance - body.AmountToSubtract
	dbTx.Save(&object)

	// create new object
	// generate a pin
	countryCallCode := config.CurrencyCallCodes[strings.ToUpper(object.Service.Identity.BaseCurrency)]
	newPin, err := services.NewObjectPin(strconv.Itoa(countryCallCode))
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	newObj := NewObject(newPin, models.ObjectValue, object.Service, object.Wallet, body.AmountToSubtract, body.Meta)
	err = models.CreateObject(dbTx, &newObj)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:object.go

示例14: Divide

// divide an object into two or more equal parts.
// maxinum of 100 equal parts is allowed.
// object to be splitted must belong to authorizing wallet
func (c *ObjectController) Divide(res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// authorizing wallet id
	// todo: get from access token
	authWalletID := "55c679145fe09c74ed000001"

	// parse body
	var body objectDivideBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// object is required
	if c.validate.IsEmpty(body.Object) {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: object")
		return
	}

	// number of objects must be greater than 1
	if body.NumObjects < 2 {
		services.Res(res).Error(400, "invalid_parameter", "num_objects: must be greater than 1")
		return
	}

	// number of objects must not be greater than 100
	if body.NumObjects > 100 {
		services.Res(res).Error(400, "invalid_parameter", "num_objects: must be greater than 1")
		return
	}

	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// get the object
	object, found, err := models.FindObjectByObjectID(dbTx, body.Object)
	if !found {
		dbTx.Rollback()
		services.Res(res).Error(404, "not_found", "object was not found")
		return
	} else if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure object is a valuable type
	if object.Type == models.ObjectValueless {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_parameter", "object: object must be a valuabe type (obj_value) ")
		return
	}

	// ensure object has enough balance (minimum of 0.000001)
	if object.Balance < 0.000001 {
		dbTx.Rollback()
		services.Res(res).Error(400, "invalid_parameter", "object: object must have a minimum balance of 0.000001")
		return
	}

	// ensure object belongs to authorizing wallet
	if object.Wallet.ObjectID != authWalletID {
		dbTx.Rollback()
		services.Res(res).Error(401, "unauthorized", "object does not belong to authorizing wallet")
		return
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !body.InheritMeta && !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		services.Res(res).Error(400, "invalid_meta_size", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	} else {
		if body.InheritMeta {
			body.Meta = object.Meta
		}
	}

	// calculate new balance per object
	newBalance := object.Balance / float64(body.NumObjects)

	// delete object
	dbTx.Delete(&object)

	// create new objects
	newObjects := []models.Object{}
	for i := 0; i < body.NumObjects; i++ {

		// generate a pin
		countryCallCode := config.CurrencyCallCodes[strings.ToUpper(object.Service.Identity.BaseCurrency)]
		newPin, err := services.NewObjectPin(strconv.Itoa(countryCallCode))
		if err != nil {
			dbTx.Rollback()
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:object.go

示例15: Merge

// merge two or more objects.
// Only a max of 100 identitcal objects can be merged.
// All objects to be merged must exists.
// Only similar objects can be merged.
// Meta is not retained. Optional "meta" parameter can be
// provided as new meta for the resulting object
// TODO: Needs wallet authorization with scode "obj_merge"
func (c *ObjectController) Merge(res http.ResponseWriter, req services.AuxRequestContext, log *config.CustomLog, db *services.DB) {

	// authorizing wallet id
	// TODO: get this from the access token
	authWalletID := "55c679145fe09c74ed000001"

	// parse body
	var body objectMergeBody
	if err := c.ParseJsonBody(req, &body); err != nil {
		services.Res(res).Error(400, "invalid_body", "request body is invalid or malformed. Expects valid json body")
		return
	}

	// objects field is required
	if body.Objects == nil {
		services.Res(res).Error(400, "missing_parameter", "Missing required field: objects")
		return
	}

	// objects field must contain at least two objects
	if len(body.Objects) < 2 {
		services.Res(res).Error(400, "invalid_parameter", "objects: minimum of two objects required")
		return
	}

	// objects field must not contain more than 100 objects
	if len(body.Objects) > 100 {
		services.Res(res).Error(400, "invalid_parameter", "objects: cannot merge more than 100 objects in a request")
		return
	}

	// ensure objects contain no duplicates
	if services.StringSliceHasDuplicates(body.Objects) {
		services.Res(res).Error(400, "invalid_parameter", "objects: must not contain duplicate objects")
		return
	}

	// if meta is provided, ensure it is not greater than the limit size
	if !c.validate.IsEmpty(body.Meta) && len([]byte(body.Meta)) > MaxMetaSize {
		services.Res(res).Error(400, "invalid_meta_size", fmt.Sprintf("Meta contains too much data. Max size is %d bytes", MaxMetaSize))
		return
	}

	// get db transaction object
	dbTx, err := db.GetPostgresHandleWithRepeatableReadTrans()
	if err != nil {
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// find all objects
	objectsFound, err := models.FindAllObjectsByObjectID(dbTx, body.Objects)
	if err != nil {
		dbTx.Rollback()
		c.log.Error(err.Error())
		services.Res(res).Error(500, "", "server error")
		return
	}

	// ensure all objects where found
	if len(objectsFound) != len(body.Objects) {
		dbTx.Rollback()
		services.Res(res).Error(400, "unknown_merge_objects", "one or more objects does not exists")
		return
	}

	totalBalance := 0.0
	firstObj := objectsFound[0]
	checkObjName := firstObj.Service.Identity.ObjectName

	for _, object := range objectsFound {

		// ensure all objects are valuable and also ensure object's
		if object.Type == models.ObjectValueless {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "objects: only valuable objects (object_value) can be merged")
			return
		}

		// wallet id match the authorizing wallet id
		if object.Wallet.ObjectID != authWalletID {
			dbTx.Rollback()
			services.Res(res).Error(401, "unauthorized", "objects: one or more objects belongs to a different wallet")
			return
		}

		// ensure all objects are similar by their name / same issuer.
		// this also ensures all objects have the same base currency
		if checkObjName != object.Service.Identity.ObjectName {
			dbTx.Rollback()
			services.Res(res).Error(400, "invalid_parameter", "objects: only similar (by name) objects can be merged")
			return
//.........这里部分代码省略.........
开发者ID:ownode,项目名称:ownode,代码行数:101,代码来源:object.go


注:本文中的github.com/ownode/services.DB类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。