GraphQL ID type correction - how to use String? - laravel

I have a model with unique id's like d192a9be-c1f8-4099-8e88-7333ca07866d
When queried using graphql the result is id: "0" so it looks like it's trying to convert to Int.
How do I use String unique ID?

Related

many to many in gorm v2 error on foreign key

I'm finding it difficult to define many to many relationship using Gorm in following cases
features(feature_id, name, slug)
operations(operation_id, name, slug)
feature_operations(feature_id, operation_id)
type Feature struct {
FeatureID int64 `gorm:"primaryKey;column:feature_id" json:"feature_id"`
Name string `validate:"required" json:"name"`
Slug string `json:"slug"`
Status string `json:"status"`
Operations []Operation `gorm:"many2many:feature_operations;foreignKey:feature_id"`
appModels.BaseModel
}
When using feature_id, I get error
column feature_operations.feature_feature_id does not exist
When using id, I get error
invalid foreign key: id
Looks like you are not using the convention that gorm suggests where you name your primary key columns just id
so in your case your foreignKey should be the name of the field and you also need to use References to specify column that you want to reference. See the example here:
https://gorm.io/docs/many_to_many.html#Override-Foreign-Key
What you need is this:
type Feature struct {
FeatureID int64 `gorm:"primaryKey;column:feature_id"`
Name string
Slug string
Operations []Operation `gorm:"many2many:feature_operations;foreignKey:FeatureID;References:OperationID"`
}
type Operation struct {
OperationID int64 `gorm:"primaryKey;column:operation_id"`
Name string
Slug string
}
After this the join table will be FEATURE_OPERATIONS with two columns FEATURE_FEATURE_ID AND OPERATION_OPERATION_ID
If you dont like the redundant column names then you need to use the two additional attributes joinForeignKey and joinReferences to choose your own names for the columns like so:
gorm:"many2many:feature_operations;foreignKey:FeatureID;joinForeignKey:FeatureID;References:OperationID;joinReferences:OperationID"
All this extra work is needed because your primary keys are FEATURE_ID and OPERATION_ID instead of just ID
If you can rename the column to follow the convention, you will notice life is much easier with gorm

Type error with Hasura array data type: "A string is expected for type : _int4"

I have a table I created in the Hasura console. A few of the columns are integer int types and I get the expected data type: Maybe<Scalars['Int']>.
However, a few needed to be an array of integers so I created those in the Hasura SQL tab:
ALTER TABLE my_table
add my_ids integer[];
If I populate those in GraphiQL with the following query variable everything works just fine:
{
"my_ids": "{1200, 1201, 1202}",
}
However, when I try to make the same request from my front-end client, I received the following error: A string is expected for type : _int4. Looking at the datatype, it is slightly different than the preset (in the data type dropdown) integer types: Maybe<Scalars['_int4']>.
Is there a way to get the array of integers to be Maybe<Scalars['Int']> like the preset integer types? Or if there isn't, how can resolve the issue with my request throwing errors for this _int4 type?
Hasura cannot process array but it can process array literals.
I've written a function to help you to transform your array into array literal before mutation:
const toArrayLiteral = (arr) => (JSON.stringify(arr).replace('[', '{').replace(']', '}'))
...
myObject.array = toArrayLiteral(myObject.array) // will make ['friend'] to {'friend'}
Good luck

Query on Array of strings to get matched values from Datastore

I have following scenario where struct is
type Band struct {
Name string `json:"name"`
Albums []String `json:"album"`
GradeLevel []string `json:"gradeLevel,omitempty"`
Topics []string `json:"topics,omitempty"`
}
Data stored like (Sample)
**Name Albums GradeLevel Topics**
Sample ["sample","Test"] ["grade1"] ["Children","Poems"]
test ["Test"] ["grade2","grade1"] ["therapy","slow"]
Here how to query to get appropriate values from Band kind with given inputs like
Request to query is {"album" : ["sample","Test"] , "gradeLevel" : ["grade1"] , "topic" : ["poem"]}
With combination of inputs are possible from front-end so how to query based input to display list of values for above scenario.
You can find information on writing queries in Go to retrieve data from Firestore in Datastore mode here [1]. To query if an array contains a value, you need to use an equality filter [2].
[1] https://cloud.google.com/datastore/docs/concepts/queries
[2] https://cloud.google.com/datastore/docs/concepts/queries#array_values

Data modelling for ecommerce website using Amplify + GraphQL + DynamoDB

I'm using Amplify from AWS to build a small ecommerce project using React as frontend.
I'd like to know how I should write the "Product" and "Order" types in the schema in order to be able to write productId's to a product array in the Order table when users complete a purchase.
My schema.graphql file:
type Product #model {
id: ID!
name: String!
price: Int!
category: String!
images: [String]!
}
type Order #model {
id: ID!
products: [Product] #connection
}
My question is about the last line, do I need to define that [Product] connection there or I can use [String] to store product id's in a simple string array?
Point 1: In dynamoDB, you only need to define the data type of your partition key and sort key, and these can be string, number etc. For all the other attributes, you don't need to define anything.
Point 2: The dynamoDB designers prefer using a single table per application, unless it's impossible to manage data without multiple tables. Keeping this in mind, your table can be something like this.
Please observe: Only Id aka partition key and Sk aka sort key column is fixed here, all other columns can be anything per item. This is the beauty of DynamoDB. Refer to this document for dynamoDB supported data types.

Graphql ID resolves as string even if it's integer

I'm new to graphql and hope someone can explain me this ID type that is always string.
As sad in docs:
The ID scalar type represents a unique identifier, often used to re-fetch an object or as a key for a cache.
If you use, for example, some caching client like Apollo, each type
should have at least one ID. This allows us to perform a normalization
of queries, making it possible for us to update things in Apollo
internal redux store automatically based on the unique id
Ok, so i can use int, but how then i get my id as integer on client side?
Reason is simple, let's say i have Book type with id of type ID and author_id relation of type Int. Also i have Author type with id of type ID. And after i fetch book and author i will have book.author_id int and author.id string, but it's the same number!
What should i do? Use everywhere ID even for many to many relations? Make new scalar ID type that can be used as ID for re-fetch but will be of type Int?
From the spec:
The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as a String... GraphQL is agnostic to ID format, and serializes to string to ensure consistency across many formats ID could represent, from small auto‐increment numbers, to large 128‐bit random numbers, to base64 encoded values, or string values of a format like GUID.
It's unclear why the client would care about comparing IDs in this context -- columns like author_id should generally be hidden from the client anyway, with the schema only exposing the related entity, not fields that are only used to link entities. That said, an ID is just an ID and a client shouldn't care whether it's a string or an integer as long as it's consistent. If you have one field returning an integer (Book.author_id) and another returning a string (Author.id), then that's a problem on the part of your schema.
The ID scalar can be used for any number of fields, not just the one field (which may or may not be named id). Similarly, if you want to use Int or String as the type for your id field you can -- this will not impact Apollo's ability to cache your results.
In apollo you can use typePolicies to determintate what field is used as unique identifier. That will resolve a pain of ID! type conversion to string.
const typePolicies = {
Book: {
keyFields: ['id'],
},
BookTag: {
keyFields: ['book_id', 'tag_id'],
}
}
return new ApolloClient({
cache: new InMemoryCache({ typePolicies }),
})

Resources