【问题标题】:How to sort by date(createdAt) on a field in list query in aws-amplify?如何按日期(createdAt)对aws-amplify中列表查询中的字段进行排序?
【发布时间】:2020-01-31 20:35:46
【问题描述】:
type Test @model @key(fields: ["id", "createdAt"]) {
  id: ID!
  name: String
  createdAt: String!
}

此模型创建了查询:

getTest(createdAt: String!id: ID!): Test

listTests(
  createdAt: ModelStringKeyConditionInput
  filter: ModelTestFilterInput
  id: ID
  limit: Int
  nextToken: String
  sortDirection: ModelSortDirection
): ModelTestConnection

请求按日期排序的列表的方案应该是什么样的?

【问题讨论】:

  • 添加代码格式

标签: amazon-web-services sorting graphql schema aws-amplify


【解决方案1】:

@key 指定多个字段时,第一个字段作为 HASH 键,后续字段作为 SORT 键。

https://aws-amplify.github.io/docs/cli-toolchain/graphql#key

可以列出具有相同 HASH 键的已排序项目。例如,按用户列出所有 cmets:

type Comment
  @model
  @key(fields: ["userId", "createdAt"]) {
    userId: ID!
    createdAt: String!
    text: String
}

假设您使用的是 AWS Amplify 的 GraphQL 客户端,这将按用户列出所有 cmets,并按最新排序:

import { API, graphqlOperation } from 'aws-amplify';
import { listComments } from '@/graphql/queries';

export default async function listCommentsForUser(userId) {
  const queryParams = {
    userId,
    sortDirection: 'DESC',
  };

  const operation = graphqlOperation(listComments, queryParams);

  return API.graphql(operation);
}

要列出自指定日期以来的 cmets,最新的在前,更改查询参数以包含范围查询:

const queryParams = {
    userId,
    sortDirection: 'DESC',
    createdAt: { gt: timestamp },
  };

【讨论】:

  • 创建时间:AWSDateTime!而不是字符串!
猜你喜欢
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
相关资源
最近更新 更多