因此,我创建了一堆突变和查询,并将它们拼接在一起,这些工作并希望将身份验证引入到组合中。我添加了一个 HTTP 标头“x-token”来保存我的登录令牌,以便能够删除他们的工作或用户本身等内容。
const getMe = async req => {
const token = req.headers['x-token'];
if (token) {
try {
return await jwt.verify(token, "notSoSecret");
} catch (e) {
throw new AuthenticationError(
'Your session expired. Sign in again.',
);
}
}
};
const server = new ApolloServer({
typeDefs: schema,
resolvers,
formatError: error => {
// remove the internal sequelize error message
// leave only the important validation error
const message = error.message
.replace('SequelizeValidationError: ', '')
.replace('Validation error: ', '');
return {
...error, …
Run Code Online (Sandbox Code Playgroud) 所以我想弄清楚为什么我的 Query 最终是:
{
"errors": [
{
"message": "Cannot return null for non-nullable field Message.sender.",
}
...
}
Run Code Online (Sandbox Code Playgroud)
这是我的实体
@Entity()
export class Message extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column("text")
content: string;
@CreateDateColumn()
created_at: string;
// @ts-ignore
@ManyToOne(type => User, user => user.messages)
sender: User;
}
Run Code Online (Sandbox Code Playgroud)
还有我的解析器:
allMessagesOfProject: async (_, { projectId }, __) => {
const project = await Project.findOne({
relations: ["messages"],
where: { id: projectId }
});
if (project) {
const messages = project.messages;
return messages.reverse();
}
return …
Run Code Online (Sandbox Code Playgroud) 我知道这已经被问了几个的时间之前,但我发现没有明确的解决方案,这是否是可能的GraphQL。我强烈认为这应该是可能的,因为它应该相对容易实现,因为 GraphQL 查询在 Apollo 中按顺序运行。
我有一种情况,我首先在客户端上执行 GraphQL 突变,然后在执行使用上一个查询结果的查询之后立即执行。这会导致等待服务器响应两个请求的响应时间过长。请求如下所示:
mutation createWebSession($authId: ID!) {
webSession: createWebSession(authId: $authId) {
token
userId
}
}
query listUserPaymentMethods($userId: ID!) {
userPaymentMethods: paymentMethods(userId: $userId) {
id
}
}
Run Code Online (Sandbox Code Playgroud)
我知道一种避免两次往返服务器的简单创可贴解决方案是创建一个新的单一 GraphQL 突变端点,该端点在后端执行这两项服务。但这似乎违背了编写模块化、可重用 GraphQL 端点的目的。因此,我很好奇是否有人知道 Apollo GraphQL 是否支持一种更简洁的方式来链接 2 个请求,其中前一个请求的结果可作为输入提供给下一个请求。
任何帮助将不胜感激,谢谢。
我有一个用作react-table
数据网格的函数。它最初是通过本地状态从父组件中的 Apollo 填充的,网格中的每一行都是数组中的对象。
当网格中的单元格发生变化时,整条线对象都会被写入状态。
我正在尝试使用 useEffect 触发一个突变,将这些状态更改写回数据库,但我正在努力解决两个主要问题:
主要功能(部分)
function Table2({ columns, data }) {
const [lines, setLines] = useState(data);
const [updateLine, {loading, error }] = useMutation(UPDATE_ITEM_MUTATION, {
variables:{ ...lines}
});
useEffect(() => {
updateLine
},[lines]);
const updateMyData = (rowIndex, columnID, value) => {
setLines(getLines =>
getLines.map((row, index) => {
if (index === rowIndex) {
console.log(row)
return {
...lines[rowIndex],
[columnID]: value
};
}
return row;
})
);
};
Run Code Online (Sandbox Code Playgroud)
还有突变……
const UPDATE_ITEM_MUTATION = gql`
mutation UPDATE_LINE_MUTATION( …
Run Code Online (Sandbox Code Playgroud) 我无法构建由 Android Apollo 库生成的查询。
我有以下 .gpaphql 文件:
mutation LogIn($username: String!, $password: String!) {
tokenAuth(username: $username, password: $password) {
token
}
}
Run Code Online (Sandbox Code Playgroud)
它为此生成了一个 Kotlin 请求文件:
// AUTO-GENERATED FILE. DO NOT MODIFY.
//
// This class was automatically generated by Apollo GraphQL plugin from the GraphQL queries it found.
// It should not be modified by hand.
//
import com.apollographql.apollo.api.InputFieldMarshaller
import com.apollographql.apollo.api.Mutation
import com.apollographql.apollo.api.Operation
import com.apollographql.apollo.api.OperationName
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.api.ResponseField
import com.apollographql.apollo.api.ResponseFieldMapper
import com.apollographql.apollo.api.ResponseFieldMarshaller
import com.apollographql.apollo.api.ResponseReader
import com.apollographql.apollo.api.internal.SimpleOperationResponseParser
import com.apollographql.apollo.internal.QueryDocumentMinifier
import com.apollographql.apollo.response.ScalarTypeAdapters …
Run Code Online (Sandbox Code Playgroud) 我的组件实例中有一个查询:
@Component({
apollo: {
cartProducts: {
query: GET_CART_PRODUCTS,
loadingKey: "loading",
},
}
})
Run Code Online (Sandbox Code Playgroud)
它正在正确加载我的数据。然后我更改数据库中的数据并希望在单击时重新获取它们,这会调用该函数:
refresh() {
this.$apollo
.query({
query: GET_CART_PRODUCTS,
})
.then((res: any) => (this.cartProducts = res.data.cartProducts))
.catch((err: any) => console.log(err));
}
Run Code Online (Sandbox Code Playgroud)
但它不会更新cartProducts
属性,也不会给我任何错误。虽然如果我刷新页面,就会有新数据。在我的 Apollo 配置中,我有这样的属性fetchPolicy: "network-only"
。这种行为的原因可能是什么?提前致谢!
所以我知道我可以使用 ctx.req.headers.cookie 访问我的 cookie 服务器端,但我不确定如何使用 Apollo Client 将该 cookie 发送到我的 GraphQL 端点。
有什么帮助吗?谢谢。
假设我有以下 GraphQL 类型:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}
Run Code Online (Sandbox Code Playgroud)
这是返回更新后的帖子的突变:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}
Run Code Online (Sandbox Code Playgroud)
运行此突变后,我的缓存包含帖子的新条目。如何将其添加到用户的帖子数组中?我尝试过cache.writeQuery和cache.modify但我无法弄清楚。
我想通过 GrahQL 和 React 保存一个大表单。我将所有表单值都放在一个变量名中:formValue 有没有办法将“formValue”传递给这样的查询?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($profileId: String!) {
updateProfile(profile: { formValue }) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
或者我应该一一传递所有字段并像这样定义它们的类型?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......) {
updateProfile(profile: { id: $id, firstName: $firstName, lastName: $lastName, age:$age, ......}) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
模式看起来像这样
updateProfile(profile: ProfileDTOInput!): ProfileDTO
type ProfileDTO {
address: String …
Run Code Online (Sandbox Code Playgroud) 我正在使用带有 prisma 和 typegraphql 的 typescript 并收到此类型错误。RatesWhereUniqeInput 由 prisma 生成,并将自身定义为“CompoundUniqueInput”,因为我引用的数据库有 2 个键(clientId:字符串,employeeId:数字)。
在我的存储库中,我想使用这两个方法来使用“update()”引用特定的数据库行,但因为该类型是在 prisma 客户端中生成的 clientId_employeeId?我收到类型错误。
储存库功能
async update(model: Rates): Promise<Rates> {
const { employeeId, clientId, ...data } = this.mapper.from(model);
const entity = await this.db.rates.update({
where: { employeeId, clientId },
data: {
...data,
},
});
return this.mapper.to(entity);
}
Run Code Online (Sandbox Code Playgroud)
Prisma 索引.d.ts
export type RatesWhereUniqueInput = {
clientId_employeeId?: RatesClientIdEmployeeIdCompoundUniqueInput
}
Run Code Online (Sandbox Code Playgroud)
费率映射器.ts
@injectable()
export class RatesMapper {
public from(model: Rates): RatesEntity {
return {
employeeId: model.employeeId,
clientId: model.clientId,
rateFull: model.rateFull,
rateQuarter: model.rateQuarter,
rateLine: …
Run Code Online (Sandbox Code Playgroud) graphql
我在我的应用程序上使用 Apollo Client 作为客户端next.js
,以下是为我创建客户端的函数:
let client: ApolloClient<any>;
export const __ssrMode__: boolean = typeof window === "undefined";
export const uri: string = "http://localhost:3001/graphql";
const createApolloClient = (): ApolloClient<any> => {
return new ApolloClient({
credentials: "include",
ssrMode: __ssrMode__,
link: createHttpLink({
uri,
credentials: "include",
}),
cache: new InMemoryCache(),
});
};
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,当我对 graphql 服务器进行更改时,我能够设置 cookie,但是我无法从客户端获取 cookie。可能是什么问题?
我正在关注阿波罗教程(https://www.apollographql.com/docs/tutorial/resolvers/),我看到了这个代码:
me: async (_, __, { dataSources }) =>
dataSources.userAPI.findOrCreateUser()
Run Code Online (Sandbox Code Playgroud)
因为dataSources.userAPI.findOrCreateUser()
返回Promise,我认为这await dataSources.userAPI.findOrCreateUser()
是对的。
但是它运行得非常好,没有任何错误,我在 React 中得到了解决的价值……即使是下面的代码也运行得很好。
me: (_, __, { dataSources }) =>
dataSources.userAPI.findOrCreateUser()
Run Code Online (Sandbox Code Playgroud)
这段代码让我很困惑。它是如何工作的?
apollo ×12
graphql ×8
reactjs ×3
next.js ×2
node.js ×2
typescript ×2
android ×1
async-await ×1
asynchronous ×1
express ×1
javascript ×1
kotlin ×1
prisma ×1
react-apollo ×1
sequelize.js ×1
serverless ×1
typegraphql ×1
typeorm ×1
vue-apollo ×1
vue.js ×1