list-query-plugin.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { Args, Query, Resolver } from '@nestjs/graphql';
  2. import { InjectConnection } from '@nestjs/typeorm';
  3. import {
  4. ListQueryBuilder,
  5. OnVendureBootstrap,
  6. PluginCommonModule,
  7. VendureEntity,
  8. VendurePlugin,
  9. } from '@vendure/core';
  10. import gql from 'graphql-tag';
  11. import { Column, Connection, Entity } from 'typeorm';
  12. @Entity()
  13. export class TestEntity extends VendureEntity {
  14. constructor(input: Partial<TestEntity>) {
  15. super(input);
  16. }
  17. @Column()
  18. label: string;
  19. @Column()
  20. date: Date;
  21. }
  22. @Resolver()
  23. export class ListQueryResolver {
  24. constructor(private listQueryBuilder: ListQueryBuilder) {}
  25. @Query()
  26. testEntities(@Args() args: any) {
  27. return this.listQueryBuilder
  28. .build(TestEntity, args.options)
  29. .getManyAndCount()
  30. .then(([items, totalItems]) => {
  31. return {
  32. items,
  33. totalItems,
  34. };
  35. });
  36. }
  37. }
  38. const adminApiExtensions = gql`
  39. type TestEntity implements Node {
  40. id: ID!
  41. createdAt: DateTime!
  42. updatedAt: DateTime!
  43. label: String!
  44. date: DateTime!
  45. }
  46. type TestEntityList implements PaginatedList {
  47. totalItems: Int!
  48. items: [TestEntity!]!
  49. }
  50. extend type Query {
  51. testEntities(options: TestEntityListOptions): TestEntityList!
  52. }
  53. input TestEntityListOptions
  54. `;
  55. @VendurePlugin({
  56. imports: [PluginCommonModule],
  57. entities: [TestEntity],
  58. adminApiExtensions: {
  59. schema: adminApiExtensions,
  60. resolvers: [ListQueryResolver],
  61. },
  62. })
  63. export class ListQueryPlugin implements OnVendureBootstrap {
  64. constructor(@InjectConnection() private connection: Connection) {}
  65. async onVendureBootstrap() {
  66. const count = await this.connection.getRepository(TestEntity).count();
  67. if (count === 0) {
  68. await this.connection
  69. .getRepository(TestEntity)
  70. .save([
  71. new TestEntity({ label: 'A', date: new Date('2020-01-05T10:00:00.000Z') }),
  72. new TestEntity({ label: 'B', date: new Date('2020-01-15T10:00:00.000Z') }),
  73. new TestEntity({ label: 'C', date: new Date('2020-01-25T10:00:00.000Z') }),
  74. ]);
  75. }
  76. }
  77. }