Open BethanyG opened 8 years ago
When scaffolding a beego api, the following controller logic is created:
// @Title create
// @Description create object
// @Param body body models.Object true "The object content"
// @Success 200 {string} models.Object.Id
// @Failure 403 body is empty
// @router / [post]
func (o *ObjectController) Post() {
var ob models.Object
json.Unmarshal(o.Ctx.Input.RequestBody, &ob)
objectid := models.AddOne(ob)
o.Data["json"] = map[string]string{"ObjectId": objectid}
o.ServeJSON()
}
Building off your api call code @BethanyG , this should be a good place to start building CURD. To check out the other router and model logic, run bee api
to get the full codebase.
Have you got a working example of this in your code? If so, I'd love to see it. I've managed to make a post() and a get() that hit the db and return a []struct that's Marshalled into JSON -- but when I try to do that from React, the request doesn't got through to the DB, and the resulting request object in js is null. But I'm not Unmarshalling the Ctx.Input.RequestBody server side before calling my query code -- which is probably the issue. I'll try that and see if it resolves the problem. Thanks!
The way I make server requests from a react component is like this within a react function:
this.serverRequest = //request here
Within a request, since we're returning a promise from our object, our requests will be structured something like this:
Images
.post(obj)
.then(result => {
/*
do stuff with data here...
*/
})
.catch(err => {
console.error(err);
});
This way, you can catch errors in the dev console to debug.
Per our conversation on Slack here is my current controller code (not checked in):
package controllers
import (
"fmt"
"github.com/astaxie/beego"
//"strings"
bc "todos/controllers/baseController"
)
type ActorsController struct {
bc.BaseController
}
func (this *ActorsController) RequestMovieList() {
actor := this.GetString("3")
fmt.Print(actor)
if actor == "" {
this.Ctx.WriteString("no actor listed")
beego.Error("no actor listed")
return
}
resultSet := this.QueryAllNodes(actor)
this.Data["json"] = &resultSet
this.ServeJSON()
}
func (this *ActorsController) GetMovieList() {
resultSet := this.QueryAllNodes("William Shatner")
this.Data["json"] = &resultSet
this.ServeJSON()
}
I have also made the following change in the routers file, which appears to have broken my tests:
package routers
import (
"github.com/astaxie/beego"
"todos/controllers"
)
func init() {
// Set Static Paths to bower and npm
beego.SetStaticPath("/bower", "bower_components")
// Images
beego.Router("/api/images", &controllers.ImageController{})
// Actors as test of DB queries
beego.Router("/api/actors", &controllers.ActorsController{}, "get:GetMovieList")
// Route to index.tpl
beego.Router("/", &controllers.MainController{})
}
Complete Basic CRUD Images api in beego framework and add appropriate tests to confirm functionality.