I can query a graphql object like this
info {
firstname
lastname
phone
email
}
I want to create an object contactInfo so I can query contactInfo and put phone and email inside that.
info {
firstname
lastname
...contactInfo
}
fragment contactInfo on person {
contactInfo: {
phone
email
}
}
but this keeps giving me error, how can I use fragment to put phone and email inside contactInfo?
You should check your person definition and verify is written correctly.
Then you should put inside your fragment just the fields that are in that definition.
With the info provided I think that you should remove the contacInfo field, that name is alredy defined with the sentence fragment contactInfo on person
fragment contactInfo on person {
phone
email
}
Related
I have these 2 structs
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
gorm.Model
Name string
Adress string
}
I want to get users and preload their companies but I don't want to get the Adress field I tried the custom preload like bellow and I tested it in postman . the query returned all the fields but for adress I get an empty string , the reason why this is happening is that when storing the result in the user struct golang automatically initialize all the fields and the field adress get returned with its initial value which is an empty sting
var user []User
db.Table("users").Preload("Company",func(db *gorm.DB) *gorm.DB {
return db.Select("ID" ,"Name")
}).Find(&user)
what should I do to only have the name and id but not the adress
If your server exports the result as json you could add the json tag omitempty as such:
type Company struct {
gorm.Model
Name string
Adress string `json:"omitempty"`
}
That way the address field will not be included if it is an empty string.
Lets say i have the following query:
query getBooksQuery($userId: String) {
getBooks(userId: $userId) {
id
description
image
user {
email
firstName
lastName
image
}
}
}
Imagine i have to show a list with books of a user and display the author details above the list. Since I'm querying with a userId, i know that all books belong to the same user.
So, i would not like to get for each book of the list the same user details, but get them only once in the response.
Is there any way to declare that i want these info only for the first book i.e.?
Or is it the only way to have two objects in the response, like:
query getBooksQuery($userId: String) {
getBooks(userId: $userId) {
books {
id
description
image
}
user {
email
firstName
lastName
image
}
}
}
Unfortunately with the second solution, even if its clearer at this point, will require server-side work to support this custom query. So i was thinking if it is still feasible using the current api.
(Also ofc i can do two requests, one for the user and one for the books, but meh...)
I'm using Apollo without relay, but I'm experimenting at this point, so if not feasible in Apollo but feasible otherwise I'm still interested
You can use the same param for 2 'subqueries' in one request
query getBooksQuery($userId: String) {
getBooks(userId: $userId) {
books {
id
description
image
}
}
getUsers(userId: $userId) {
user {
email
firstName
lastName
image
}
}
}
I want to create a model User and Social where the User model has many Socials. Ideally a Social type would also have has one relation to simpilify querying from either side. Here is a code sample:
database type is MySQL 8.0
type base struct {
ID string `json:"id" gorm:"type:char(36);primaryKey;"`
Created time.Time `json:"created" gorm:"autoCreateTime"`
Updated time.Time `json:"updated" gorm:"autoUpdateTime"`
}
type User struct {
base
Friends []*User `json:"friends" gorm:"many2many:friends"`
Socials []*Social `json:"socials"`
}
type Social struct {
base
Provider string `json:"provider" gorm:"type:varchar(32);index"`
Identifier string `json:"identifier" gorm:"type:varchar(32);index"`
User *User `json:"user" gorm:"foreignKey:ID"`
Token string `json:"token"`
Link string `json:"link" gorm:"type:varchar(128)"`
}
Im getting the following error when using db.AutoMigrate(&User{}, &Social{}):
model.Social's field User, need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface
runtime error: invalid memory address or nil pointer dereference
I have tried:
adding gorm:"foreignKey:ID" to User.Socials tags
not using pointers (eg in User struct Socials []Social instead of Socials []*Social)
but the issue remains
According to documentation (https://gorm.io/docs/has_many.html#Has-Many),
you need to use objects, not references
type User struct {
base
Friends []User `json:"friends" gorm:"many2many:friends"`
Socials []Social `json:"socials"`
}
no * here
Also you can add UserID field to Social
type Social struct {
base
UserID string
Provider string `json:"provider" gorm:"type:varchar(32);index"`
Identifier string `json:"identifier" gorm:"type:varchar(32);index"`
User *User `json:"user" gorm:"foreignKey:ID"`
Token string `json:"token"`
Link string `json:"link" gorm:"type:varchar(128)"`
}
and add
type User struct {
base
FriendOf string `gorm:""`
Friends []*User `json:"friends" gorm:"many2many:friends,foreignKey:FriendOf"`
Socials []*Social `json:"socials"`
}
Issue was here:
type base struct {
...
}
type User {
base
...
}
type Social {
base
...
}
Since I thought base would just be package local definition I messed up the capitalization and had a private primary key.
Another issue was touched on by #vodolaz095, but (imo) not sufficiently clarified for any new go-gorm user.
It does not seem to be possible to use a has one relation like User User be the foreign key for a has many relation like Socials []Social gorm:"foreignKey:User". It is required to be split up as #vodolaz095 displayed in his 2nd code block
I have coded in C# for years, but I am new to ASP.NET Core. I have created a Web API where I generated my Model classes from an existing database and used the scaffolding to create a Controller for each model that gives me Get, Put, Post, and Delete. My question is how do I know if the caller is clearing a value vs the value is the default for the C# object?
For example, in Vue.js I send
var sendstuff = {userName: "TestUser1", userId: 7, email: null};
In C#, my user object has
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FavoriteColor { get; set; }
In my controller, my put method begins
public async Task<IActionResult> PutUsers([FromRoute] int id, [FromBody] User user)
My User instance in the database is TestUser1, 7, test#test.com, purple. The User that comes into PutUsers is TestUser1, 7, null, null.
At this point, I want to compare the values sent in for user 7 to the values in the database for user 7. However, since both FavoriteColor (that is not sent) and Email (that is sent) look the same as they both appear as null, how do I know whether or not it should be changed? I want test#test.com to be cleared, but I want purple to remain.
It seems my only other option is to have Vue.js send in every single column for every table, with the values either the original value I don't want changed or the new value. This doesn't feel right.
Am I missing something?
Thanks in advance!
The only way I can think of is to accept a Generic Json-Object and checking wether or not the Properties are set.
Most Json Frameworks will be able to cast to a specific Object from the Json Object so you won't even need to change your further code.
I have a Razor MVC3 project which has two user records in a form, one for the key contact and one for a backup contact. For example;
public class User
{
[Required(ErrorMessage = "First name is required")]
public string FirstName { get; set; }
}
Validation all works well except for the small issue where the user fails to fill out a field, it says 'First name is required' but I'd like to point the user to which one of the first name fields is missing. Such as 'Backup contact first name is required' or 'Key contact first name is required'.
Ideally I'd like to leave the [Required] annotation on the class as it is used elsewhere.
This seems like one of those small cases that might have been missed and is not easily achieved, but please prove me wrong.
Ryan
One way you can accomplish this is with a separate view model for this screen, instead of a single User model with all the error messages. In the new view model, you could have a BackupContactFirstName property, KeyContactFirstName property, etc each with its separate error message. (Alternatively this view model could contain separate User models as properties, but I've found that Microsoft's client validation doesn't play well with complex models and prefers flat properties).
Your view model would look like this:
public class MySpecialScreenViewModel
{
[Required(ErrorMessage = "Backup contact first name is required")]
public string BackupContactFirstName { get; set; }
[Required(ErrorMessage = "Key contact first name is required")]
public string KeyContactFirstName { get; set; }
}
Then pass your view model to the view like this:
#model MySpecialScreenViewModel
...
Your post controller action would collect the properties from the view model (or map them to separate User models) and pass them to the appropriate data processing methods.
An alternative I have stumbled across, just modify the ModelState collection. It will have the elements in a collection named by index, like 'User_0__EmailAddress' and you can adjust / amend / replace the Errors collection associated with that key.
[Required(ErrorMessage = "{0} is required")]
{0}=The DisplayName is automatically placed on it
sample
[DisplayName("Amount per square meter")]
[Required(ErrorMessage = "{0} is required")]
public int PriceMeter { get; set; }
output
Amount per square meter is required