Set up the background
In a project, the structure of a request that contains three permissions, which can be arbitrarily combined
At first I thought
This operation is a bit dirty, I have prepared the template of various permission combinations in advance? On second thought I might need to prepare for the following
Permission to A | Permission to B | Permission to C |
---|---|---|
X | X | X |
X | X ️ | ✔ ️ |
X | ✔ ️ | ✔ ️ |
✔ ️ | ✔ | ✔ |
✔ | ✔ | X |
✔ | X | X |
X | ✔ | X |
✔ | X | ✔ |
There are these 8, if the time comes and I add a permission, is not to die in situ. Then I considered the GQL function to directly pass the template, through the template filtering to generate the template we want, so I looked at the usage.
/ / this
import gql from 'graphql-tag'
const t = gql` query Demo { } `
// Support fragment transmission
const t2 = gql` query Demo { ... Fragment }${Fragment}
`
Copy the code
After looking around for a long time, I couldn’t find the result I wanted, so I went to the source code of GraphQL-Tag, as shown below
Here we see a literals variable, which is the template passed in as the first argument to the GQL function, but if we use it directly as follows
gql(` query Demo { ... Fragment } `, Fragment)
Copy the code
Literals is a pure string. If we go to the concatenation args below, we can assume that result will get some unexplained character added to it, resulting in a parseDocument error, so we need to pause for a moment. We need to understand the difference between ordinary function calls and string template function calls
The difference between function calls
I will simply print arguments for the two function calls for you to see
The normal function is a string. The template string function is an array containing an original template and a placeholder that is passed in
The results of
So here we have the idea of dynamic template, we just need to construct a template string of the same structure as the first parameter in GQL ok
export function stringRaw(template, args = 0) {
const r = new Array(args)
if(r.length ! = =0) {
r.fill(' ')
}
r.unshift(template)
return r
}
const t = gql(stringRaw(`
query Demo{
field1
${permissionA ? 'field2' : ' '}
${permissionB ? 'field3' : ' '}
${permissionC ? 'field4' : ' '}field5 { ... Fragment } } `.1), Fragment)
Copy the code
So we’re done passing in dynamic strings