func Create()

in iot-onboarding-service/src/cloudrack-lambda-fn/usecase/usercase.go [15:43]


func Create(rq model.Request, dynSvc db.DBConfig, iotCore iot.Config, mqttEndpoint string) (model.Response, error) {
	//0-Checking if device with identical serial number exists. if yes we retuurn the Response
	log.Printf("[ONBOARDING][CREATE] checking if device has already been onboarded")
	res, err0 := Retrieve(rq, dynSvc, mqttEndpoint)
	//if the device has already been onboarded, we return the data directly, this allows teh service
	//to be idempotent which facilitates retry strategy
	if err0 == nil {
		log.Printf("[ONBOARDING][CREATE] device has already been onboarded")
		return res, nil
	}
	//0-Create the device using IOT Core SDK
	//TODO: make the device name prefix customizable in query
	log.Printf("[ONBOARDING][CREATE] Device does not exists, creating it")
	iotCredentals, err := iotCore.CreateDevice(rq.SerialNumber)
	if err != nil {
		return model.Response{}, err
	}
	//1-Create record in DynamoDB
	log.Printf("[ONBOARDING][CREATE] Creation success, Adding to DynamoDB")
	dynamoRecord := adapter.RequestToDynamo(rq, iotCredentals)
	_, err2 := dynSvc.Save(dynamoRecord)
	if err2 != nil {
		return model.Response{}, err2
	}
	//2-Build response
	log.Printf("[ONBOARDING][CREATE] Returning response")
	response := adapter.CreateResponse(rq, iotCredentals, mqttEndpoint)
	return response, nil
}