[英]Websocket connection with apollo-server returns gibberish for connectionParams
[英]Apollo-server 2 validation middleware
我想在apollo服務器上添加驗證層。 它應該在每個graphql查詢/變異之后但在解析器函數之前運行。 驗證層需要知道被調用的graphql查詢/變異和傳遞的參數。 如果它無效則會拋出錯誤並阻止解析器函數運行。
我不清楚在沒有手動將其放入每個解析器功能的情況下將其注入的位置。
graphql-tools
實際上包含一個addSchemaLevelResolveFunction
實用程序,它允許您為每個Query
, Mutation
和Subscription
字段包裝解析器以模擬“根級解析器”:
const {makeExecutableSchema,addSchemaLevelResolveFunction} = require('graphql-tools')
const schema = makeExecutableSchema({ resolvers, typeDefs })
const rootLevelResolver = (root, args, context, info) => {
// Your validation logic here. Throwing an error will prevent the wrapped resolver from executing.
// Note: whatever you return here will be passed as the parent value to the wrapped resolver
}
addSchemaLevelResolveFunction(schema, rootLevelResolver)
這是將一些邏輯應用於所有根級別字段的簡單方法,但如果只有一些字段要應用此邏輯,則會有點毛茸茸。 如果是這種情況,現在您必須維護列入白名單或列入黑名單的字段,與您的架構分開。 如果您團隊中的其他人正在添加新字段並且不了解此機制,這可能會很麻煩。 如果要將相同的邏輯應用於根級別之外的字段,那么它也不是非常有用。
更好的方法是使用自定義模式指令, 如文檔中所述 。 這允許您指示將邏輯應用於哪些字段:
directive @customValidation on FIELD_DEFINITION
type Query {
someField: String @customValidation
someOtherField: String
}
您可以在
context
中添加驗證方法,您也可以在context
中獲取請求參數,查詢,標題等您還可以考慮實現可以在架構級別應用的自定義指令。
參考https://www.apollographql.com/docs/apollo-server/features/authentication.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.