apollo-server#gql TypeScript Examples

The following examples show how to use apollo-server#gql. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: root.ts    From vt-api with GNU Affero General Public License v3.0 6 votes vote down vote up
root = gql`
  scalar JSON
  scalar DateTime
  type Query {
    root: String
  }
  directive @rateLimit(
    max: Int,
    window: String,
    message: String,
    identityArgs: [String],
    arrayLengthField: String
  ) on FIELD_DEFINITION
`
Example #2
Source File: DatabaseData.ts    From vt-api with GNU Affero General Public License v3.0 6 votes vote down vote up
typeDef = gql`
  type DataObject {
    organizations: [String]!
    channels: Int!
    videos: Int!
  }
  extend type Query {
    data(
      channel_id: [ID]
      exclude_channel_id: [ID]
      organizations: [String]
      exclude_organizations: [String]
    ): DataObject!
    @rateLimit(window: "1s", max: 10, message: "You are doing that too often.")
  }
`
Example #3
Source File: server.ts    From serverless-typescript-graphql-netlify-starter with MIT License 5 votes vote down vote up
typeDefs = gql`
  type Query {
    hello: String
  }
`
Example #4
Source File: getGqlTypeDefs.ts    From one-platform with MIT License 5 votes vote down vote up
export default function getGqlTypeDefs(module: string) {
  return gql(readFileSync(module, { encoding: 'utf-8' }));
}
Example #5
Source File: newsletter.resolver.test.ts    From Cromwell with MIT License 5 votes vote down vote up
describe('product-showcase.resolver', () => {

    let server: ApolloServer;

    beforeAll(async () => {
        const schema = await buildSchema({
            resolvers: [PluginProductShowcaseResolver],
            validate: false,
            authChecker: () => true,
        });

        server = new ApolloServer({
            schema,
            context: (): TGraphQLContext => {
                return {
                    user: {
                        id: 'test',
                        email: '[email protected]',
                        role: 'administrator',
                    }
                }
            }
        });
    })

    it(`pluginProductShowcase`, async () => {
        const res = await server.executeOperation({
            query: gql`
                query pluginProductShowcase($slug: String) {
                    pluginProductShowcase(slug: $slug) {
                        elements {
                            name
                        }
                    }
                }
           `,
            variables: { slug: null }
        });
        const data = res?.data?.pluginProductShowcase?.elements;

        expect(data.length).toBe(2);
    });

})
Example #6
Source File: newsletter.resolver.test.ts    From Cromwell with MIT License 5 votes vote down vote up
describe('plugin-newsletter.resolver', () => {

    let server: ApolloServer;

    beforeAll(async () => {
        const schema = await buildSchema({
            resolvers: [PluginNewsletterResolver],
            validate: false,
            authChecker: () => true,
        });

        server = new ApolloServer({
            schema,
            context: (): TGraphQLContext => {
                return {
                    user: {
                        id: 'test',
                        email: '[email protected]',
                        role: 'administrator',
                    }
                }
            }
        });
    })

    it(`pluginNewsletterExport`, async () => {
        const res = await server.executeOperation({
            query: gql`
                query pluginNewsletterExport {
                    pluginNewsletterExport {
                        email
                    }
                }
           `
        });
        const newsletters = res?.data?.pluginNewsletterExport;

        expect(newsletters.length).toBe(2);
    });

    it(`pluginNewsletterStats`, async () => {
        const res = await server.executeOperation({
            query: gql`
                query pluginNewsletterStats {
                    pluginNewsletterStats
                }
           `
        });
        const stats = res?.data?.pluginNewsletterStats;

        expect(stats + '').toBe(2 + '');
    });

})
Example #7
Source File: VideoObject.ts    From vt-api with GNU Affero General Public License v3.0 5 votes vote down vote up
typeDef = gql`
  type PageInfo {
    total_results: Int!
    results_per_page: Int!
  }
  type VideosResource {
    items: [VideoObject]!
    next_page_token: String
    page_info: PageInfo!
  }
  type VideoObject {
    _id: ID!
    platform_id: PlatformId!
    channel_id: ID!
    organization: String!
    title: String!
    time: Time
    status: VideoStatus!
    viewers: Float
  }
  type Time {
    published: DateTime
    scheduled: DateTime
    start: DateTime
    end: DateTime
    duration: Float
  }
  enum PlatformId {
    yt
    bb
    tt
  }
  enum VideoStatus {
    live
    upcoming
    ended
    uploaded
    missing
  }
  input SortVideosFields {
    published: Sort
    scheduled: Sort
    start: Sort
    duration: Sort
  }
  extend type Query {
    live(
      organizations: [String]
      exclude_organizations: [String]
      platforms: [PlatformId]
    ): [VideoObject]!
    @rateLimit(window: "1s", max: 10, message: "You are doing that too often.")
    videos(
      channel_id: [ID]
      status: [VideoStatus]
      title: String
      organizations: [String]
      exclude_organizations: [String]
      platforms: [PlatformId]
      max_upcoming_mins: Int = 0
      order_by: SortVideosFields = { published: desc }
      page_token: String
      limit: Int = 25
    ): VideosResource!
    @rateLimit(window: "1s", max: 10, message: "You are doing that too often.")
  }
`
Example #8
Source File: ChannelObject.ts    From vt-api with GNU Affero General Public License v3.0 5 votes vote down vote up
typeDef = gql`
  type ChannelsResource {
    items: [ChannelObject]!
    next_page_token: String
    page_info: PageInfo!
  }
  type ChannelObject {
    _id: ID!
    name: Names!
    organization: String!
    platform_id: PlatformId!
    channel_name: String
    channel_id: ID!
    details: JSON
    channel_stats: ChannelStats
    description: String
    thumbnail: String
  }
  type Names {
    en: String!
    jp: String
    kr: String
    cn: String
  }
  type ChannelStats {
    published_at: DateTime
    views: Float
    subscribers: Float
    videos: Float
  }
  input SortChannelsFields {
    _id: Sort
    published_at: Sort
    subscribers: Sort
  }
  enum Sort {
    asc
    desc
  }
  extend type Query {
    channels(
      _id: [ID]
      name: String
      organizations: [String]
      exclude_organizations: [String]
      platforms: [PlatformId]
      exclude_channel_id: [ID]
      channel_id: [ID]
      order_by: SortChannelsFields = { _id: asc }
      page_token: String
      limit: Int = 25
    ): ChannelsResource!
    @rateLimit(window: "1s", max: 10, message: "You are doing that too often.")
  }
`
Example #9
Source File: attribute.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Attribute resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('attribute');
        crwClient = getGraphQLClient();
    });

    it(`getAttributes`, async () => {
        const path = GraphQLPaths.Attribute.getMany;
        const res = await server.executeOperation({
            query: gql`
                query coreGetAttributes {
                    ${path} {
                        ...AttributeFragment
                    }
                }
                ${crwClient?.AttributeFragment}
           `
        });
        const data = crwClient?.returnData(res, path);

        expect(data).toBeTruthy();
        expect(data.length).toBeTruthy();
    });

    const getAttributeById = async (attributeId: number) => {
        const path = GraphQLPaths.Attribute.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetAttributeById($attributeId: Int!) {
                ${path}(id: $attributeId) {
                    ...AttributeFragment
                }
            }
            ${crwClient?.AttributeFragment}
            `,
            variables: {
                attributeId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getAttributeById`, async () => {
        const data = await getAttributeById(1);

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    it(`updateAttribute`, async () => {
        const data1: TAttribute = await getAttributeById(1);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Attribute.update;

        const update: TAttributeInput = {
            key: data1.key,
            type: data1.type,
            icon: data1.icon,
            slug: '__test__',
            values: [],
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateAttribute($id: Int!, $data: AttributeInput!) {
                  ${path}(id: $id, data: $data) {
                      ...AttributeFragment
                  }
              }
              ${crwClient?.AttributeFragment}
          `,
            variables: {
                id: 1,
                data: update,
            }
        });
        const resInfo = crwClient?.returnData(res, path);
        expect(resInfo).toBeTruthy();
        expect(!Array.isArray(resInfo)).toBeTruthy();

        const data2 = await getAttributeById(1);

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test__').toBeTruthy();
    });


    it(`createAttribute`, async () => {
        const data1: TAttribute = await getAttributeById(1);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.Attribute.create;

        const createAttribute: TAttributeInput = {
            slug: '__test2__',
            key: data1.key,
            type: data1.type,
            icon: data1.icon,
            values: [],
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateAttribute($data: AttributeInput!) {
                  ${path}(data: $data) {
                      ...AttributeFragment
                  }
              }
              ${crwClient?.AttributeFragment}
          `,
            variables: {
                data: createAttribute,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        expect(!Array.isArray(success)).toBeTruthy();

        const data2 = await getCustomRepository(AttributeRepository).getBySlug('__test2__')

        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.slug).toBeTruthy();
        expect(data2?.slug === '__test2__').toBeTruthy();
    });


    it(`deleteAttribute`, async () => {
        const data1: TAttribute = await getAttributeById(1);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.Attribute.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteAttribute($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 1,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(!success.ValidationError).toBeTruthy();
        expect(success === true).toBeTruthy();

        const data2 = await getAttributeById(1);

        expect(!data2?.id).toBeTruthy();
        expect(!data2?.slug).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #10
Source File: coupon.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Coupon resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('coupon');
        crwClient = getGraphQLClient();
    });

    it(`getCoupons`, async () => {
        const path = GraphQLPaths.Coupon.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetCoupons($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...CouponFragment
                      }
                  }
              }
              ${crwClient?.CouponFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                } as TPagedParams<TCoupon>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length).toBeTruthy();
        expect(data.pagedMeta.pageSize).toBeTruthy();
    });

    const getCoupon = async (couponId: number): Promise<TCoupon> => {
        const path = GraphQLPaths.Coupon.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetCouponById($id: Int!) {
                ${path}(id: $id) {
                    ...CouponFragment
                }
            }
            ${crwClient?.CouponFragment}
            `,
            variables: {
                id: couponId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getCoupon`, async () => {
        const data = await getCoupon(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });

    it(`updateCoupon`, async () => {
        const data1 = await getCoupon(1);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Coupon.update;

        const inputData: TCouponInput = {
            code: '__test__',
            discountType: 'fixed',
            value: 12,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateCoupon($id: Int!, $data: CouponInput!) {
                  ${path}(id: $id, data: $data) {
                      ...CouponFragment
                  }
              }
              ${crwClient?.CouponFragment}
          `,
            variables: {
                id: 1,
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getCoupon(1);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.code).toEqual(inputData.code);
    });


    it(`createCoupon`, async () => {
        const data1: TCoupon = await getCoupon(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Coupon.create;

        const inputData: TCouponInput = {
            code: '__test__',
            discountType: 'fixed',
            value: 12,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateCoupon($data: CouponInput!) {
                  ${path}(data: $data) {
                      ...CouponFragment
                  }
              }
              ${crwClient?.CouponFragment}
          `,
            variables: {
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(CouponRepository).findOne({
            where: {
                code: inputData.code
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.code).toEqual(inputData.code);
    });


    it(`deleteCoupon`, async () => {
        const data1 = await getCoupon(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.Coupon.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteCoupon($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getCoupon(4);

        expect(!data2?.id).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #11
Source File: custom-entity.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Custom entity resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('Custom entity');
        crwClient = getGraphQLClient();

        for (let i = 0; i < 10; i++) {
            await getCustomRepository(CustomEntityRepository).createCustomEntity({
                entityType: `test_${i % 5}_${i}`,
                customMeta: {
                    test: `test_${i % 5}_${i}`,
                }
            }, i + 1);
        }
    });

    afterAll(async () => {
        await tearDownResolver(server);
    });

    const getCustomEntity = async (id: number, customMetaKeys?: string[]): Promise<TCustomEntity> => {
        const path = GraphQLPaths.CustomEntity.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetCustomEntityById($id: Int!) {
                ${path}(id: $id) {
                    id
                    entityType
                    customMeta(keys: ${JSON.stringify(customMetaKeys ?? [])})
                }
            }`,
            variables: {
                id
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    const updateEntity = async (id: number, input: TCustomEntityInput) => {
        const path = GraphQLPaths.CustomEntity.update;

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateCustomEntity($id: Int!, $data: CustomEntityInput!) {
                  ${path}(id: $id, data: $data) {
                      ...CustomEntityFragment
                  }
              }
              ${crwClient?.CustomEntityFragment}
          `,
            variables: {
                id,
                data: input,
            }
        });
        const success = crwClient?.returnData(res, path);
        return success;
    }


    const deleteEntity = async (id: number) => {
        const path = GraphQLPaths.CustomEntity.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteCustomEntity($id: Int!) {
                    ${path}(id: $id)
                }
            `,
            variables: {
                id,
            }
        });
        const success = crwClient?.returnData(res, path);
        return success;
    }


    const getFilteredCustomEntities = async (filterParams: TBaseFilter) => {
        const path = GraphQLPaths.CustomEntity.getFiltered;
        const res = await server.executeOperation({
            query: gql`
                query testGetFilteredCustomEntities($pagedParams: PagedParamsInput, $filterParams: CustomEntityFilterInput) {
                    ${path}(pagedParams: $pagedParams, filterParams: $filterParams) {
                        pagedMeta {
                            ...PagedMetaFragment
                        }
                        elements {
                            id
                            entityType
                            customMeta(keys: ["test"])
                        }
                    }
                }
                ${crwClient?.PagedMetaFragment}
            `,
            variables: {
                pagedParams: {
                    pageSize: 22,
                },
                filterParams,
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }


    it(`getCustomEntities`, async () => {
        const path = GraphQLPaths.CustomEntity.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetCustomEntities($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                            id
                            entityType
                            customMeta(keys: ["test"])
                      }
                  }
              }
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                } as TPagedParams<TCustomEntity>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length).toBeTruthy();
        expect(data.pagedMeta.pageSize).toBeTruthy();
    });


    it(`getCustomEntity`, async () => {
        const data = await getCustomEntity(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });


    it(`updateCustomEntity and meta`, async () => {
        const data1 = await getCustomEntity(1);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();


        const inputData: TCustomEntityInput = {
            entityType: 'test2',
            customMeta: {
                testUpdate: 'testUpdate'
            }
        }
        const success = await updateEntity(data1.id, inputData);

        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomEntity(data1.id, ['testUpdate']);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.entityType).toEqual(inputData.entityType);
        expect(data2.customMeta?.testUpdate).toEqual(inputData.customMeta?.testUpdate);

        await updateEntity(data1.id, {
            entityType: data1.entityType,
            customMeta: {
                testUpdate: null
            }
        });
        const data3 = await getCustomEntity(data1.id, ['testUpdate']);
        expect(data3).toBeTruthy();
        expect(data3.id).toBeTruthy();
        expect(data3.entityType).toEqual(data1.entityType);
        expect(data3.customMeta?.testUpdate).toBeFalsy();
    });


    it(`createCustomEntity`, async () => {
        const path = GraphQLPaths.CustomEntity.create;
        const inputData: TCustomEntityInput = {
            entityType: 'to_create',
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateCustomEntity($data: CustomEntityInput!) {
                  ${path}(data: $data) {
                      ...CustomEntityFragment
                  }
              }
              ${crwClient?.CustomEntityFragment}
          `,
            variables: {
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(CustomEntityRepository).findOne({
            where: {
                entityType: inputData.entityType
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.entityType).toEqual(inputData.entityType);

        await data2?.remove();
    });


    it(`deleteCustomEntity`, async () => {
        const entity = await getCustomRepository(CustomEntityRepository).createCustomEntity({
            entityType: `test_delete`,

        });
        const success = await deleteEntity(entity.id);

        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getCustomEntity(entity.id);
        expect(!data2?.id).toBeTruthy();
    });


    it(`base filter by column`, async () => {
        const data = await getFilteredCustomEntities({
            filters: [
                {
                    key: 'entityType',
                    value: 'test_3',
                    inMeta: false,
                }
            ]
        });
        expect(data.elements.length).toBe(2);
    });

    it(`base filter by column exact`, async () => {
        const data = await getFilteredCustomEntities({
            filters: [
                {
                    key: 'entityType',
                    value: 'test_3_3',
                    exact: true,
                }
            ]
        });
        expect(data.elements.length).toBe(1);
    });


    it(`base filter by meta`, async () => {
        const data = await getFilteredCustomEntities({
            filters: [
                {
                    key: 'test',
                    value: '1_',
                    inMeta: true,
                }
            ]
        });

        expect(data.elements.length).toBe(2);
    });


    it(`base filter by meta exact`, async () => {
        const data = await getFilteredCustomEntities({
            filters: [
                {
                    key: 'test',
                    value: 'test_1_1',
                    exact: true,
                    inMeta: true,
                }
            ]
        });

        expect(data.elements.length).toBe(1);
    });



    it(`base sort by column desc`, async () => {
        const data = await getFilteredCustomEntities({
            sorts: [
                {
                    key: 'entityType',
                    sort: "DESC",
                }
            ]
        });

        expect(data.elements[0].entityType).toBe(`test_4_9`);
        expect(data.elements[0].customMeta.test).toBe(`test_4_9`);
    });


    it(`base sort by column asc`, async () => {
        const data = await getFilteredCustomEntities({
            sorts: [
                {
                    key: 'entityType',
                    sort: "ASC",
                }
            ]
        });


        expect(data.elements[0].entityType).toBe(`test_0_0`);
        expect(data.elements[0].customMeta.test).toBe(`test_0_0`);
    });



    it(`base sort by meta desc`, async () => {
        const data = await getFilteredCustomEntities({
            sorts: [
                {
                    key: 'test',
                    inMeta: true,
                    sort: "DESC",
                }
            ]
        });

        expect(data.elements[0].entityType).toBe(`test_4_9`);
        expect(data.elements[0].customMeta.test).toBe(`test_4_9`);
    });

});
Example #12
Source File: generic.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Generic resolver', () => {
    // Tests via Theme resolver
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;
    const entityName = 'Plugin';
    let fragmentName;
    let fragment;

    beforeAll(async () => {
        server = await setupResolver('generic');
        crwClient = getGraphQLClient();

        fragment = crwClient?.PluginFragment;
        fragmentName = 'PluginFragment';
    });

    it(`getGeneric`, async () => {
        const path = GraphQLPaths.Generic.getMany + entityName;
        const res = await server.executeOperation({
            query: gql`
              query testGetGenerics($pagedParams: PagedParamsInput!) {
                ${path} {
                    ...${fragmentName}
                }
              }
              ${fragment}
          `,
        });
        const data = crwClient?.returnData(res, path);

        expect(data).toBeTruthy();
        expect(Array.isArray(data)).toBeTruthy();
    });

    const getGenericById = async (id: number) => {
        const path = GraphQLPaths.Generic.getOneById + entityName;
        const res = await server.executeOperation({
            query: gql`
                query testGenericGetEntityById($id: Int!) {
                    ${path}(id: $id) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                id
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    const getDefaultId = async (): Promise<number | undefined> => {
        return (await getCustomRepository(GenericPlugin.repository).find())[0]?.id;
    }
    const getDefaultSlug = async (): Promise<string | undefined | null> => {
        return (await getCustomRepository(GenericPlugin.repository).find())[0]?.slug;
    }

    it(`getGenericById`, async () => {
        const id = await getDefaultId();
        expect(id).toBeTruthy();
        if (!id) return;

        const data = await getGenericById(id);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    const getGenericBySlug = async (slug: string) => {
        const path = GraphQLPaths.Generic.getOneBySlug + entityName;
        const res = await server.executeOperation({
            query: gql`
                query testGenericGetEntityBySlug($slug: String!) {
                    ${path}(slug: $slug) {
                        ...${fragmentName}
                    }
                }
                ${fragment}
            `,
            variables: {
                slug
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getGenericBySlug`, async () => {
        const slug = await getDefaultSlug();
        expect(slug).toBeTruthy();
        if (!slug) return;

        const data = await getGenericBySlug(slug);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }
        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    it(`updateGeneric`, async () => {
        const id = await getDefaultId();
        expect(id).toBeTruthy();
        if (!id) return;

        const data1 = await getGenericById(id);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.Generic.update + entityName;

        const updateEntity: TPluginEntityInput = {
            slug: '__test__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            isInstalled: data1.isInstalled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateGeneric($id: Int!, $data: PluginInput!) {
                  ${path}(id: $id, data: $data) {
                      ...${fragmentName}
                  }
              }
              ${fragment}
          `,
            variables: {
                id: id,
                data: updateEntity,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getGenericById(id);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test__').toBeTruthy();
    });


    it(`createGeneric`, async () => {
        const id = await getDefaultId();
        expect(id).toBeTruthy();
        if (!id) return;

        const data1 = await getGenericById(id);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Generic.create + entityName;

        const createEntity: TPluginEntityInput = {
            slug: '__test3__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            isInstalled: data1.isInstalled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreatePost($data: PluginInput!) {
                  ${path}(data: $data) {
                      ...${fragmentName}
                  }
              }
              ${fragment}
          `,
            variables: {
                data: createEntity,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getGenericBySlug('__test3__');
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test3__').toBeTruthy();
    });


    it(`deleteGeneric`, async () => {
        const id = await getDefaultId();
        expect(id).toBeTruthy();
        if (!id) return;

        const data1 = await getGenericById(id);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.Generic.delete + entityName;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteGeneric($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: id,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getGenericById(id);

        expect(!data2?.id).toBeTruthy();
        expect(!data2?.slug).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #13
Source File: order.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Order resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('order');
        crwClient = getGraphQLClient();
    });

    it(`getOrders`, async () => {
        const path = GraphQLPaths.Order.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetOrders($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...OrderFragment
                      }
                  }
              }
              ${crwClient?.OrderFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                } as TPagedParams<TOrder>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length).toBeTruthy();
        expect(data.pagedMeta.pageSize).toBeTruthy();
    });

    const getOrder = async (orderId: number): Promise<TOrder> => {
        const path = GraphQLPaths.Order.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetOrderById($id: Int!) {
                ${path}(id: $id) {
                    ...OrderFragment
                }
            }
            ${crwClient?.OrderFragment}
            `,
            variables: {
                id: orderId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getOrder`, async () => {
        const data = await getOrder(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });

    it(`updateOrder`, async () => {
        const data1 = await getOrder(1);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Order.update;

        const inputData: TOrderInput = {
            customerName: '__test__',
            cartTotalPrice: 111.222,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateOrder($id: Int!, $data: OrderInput!) {
                  ${path}(id: $id, data: $data) {
                      ...OrderFragment
                  }
              }
              ${crwClient?.OrderFragment}
          `,
            variables: {
                id: 1,
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getOrder(1);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.customerName).toEqual(inputData.customerName);
    });


    it(`createOrder`, async () => {
        const data1: TOrder = await getOrder(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Order.create;

        const inputData: TOrderInput = {
            customerName: '__test2__',
            cartTotalPrice: 111.222,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateOrder($data: OrderInput!) {
                  ${path}(data: $data) {
                      ...OrderFragment
                  }
              }
              ${crwClient?.OrderFragment}
          `,
            variables: {
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(OrderRepository).findOne({
            where: {
                customerName: inputData.customerName
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.customerName).toEqual(inputData.customerName);
    });


    it(`deleteOrder`, async () => {
        const data1 = await getOrder(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.Order.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteOrder($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getOrder(4);

        expect(!data2?.id).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #14
Source File: post.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Post resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('post');
        crwClient = getGraphQLClient();
    });

    it(`getPosts`, async () => {
        const path = GraphQLPaths.Post.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetPosts($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...PostFragment
                      }
                  }
              }
              ${crwClient?.PostFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                    pageSize: 10
                } as TPagedParams<TPost>
            }
        });
        const data = crwClient?.returnData(res, path);

        expect(data).toBeTruthy();
        expect(data.elements.length === 10).toBeTruthy();
        expect(data.pagedMeta.pageSize === 10).toBeTruthy();
    });

    const getPostById = async (postId: number) => {
        const path = GraphQLPaths.Post.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetPostById($postId: Int!) {
                ${path}(id: $postId) {
                    ...PostFragment
                }
            }
            ${crwClient?.PostFragment}
            `,
            variables: {
                postId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getPostById`, async () => {
        const data = await getPostById(1);

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    const getPostBySlug = async (slug: string) => {
        const path = GraphQLPaths.Post.getOneBySlug;
        const res = await server.executeOperation({
            query: gql`
            query testGetPostBySlug($slug: String!) {
                ${path}(slug: $slug) {
                    ...PostFragment
                }
            }
            ${crwClient?.PostFragment}
            `,
            variables: {
                slug
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getPostBySlug`, async () => {
        const data = await getPostBySlug('1');

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    it(`updatePost`, async () => {
        const data1: TPost = await getPostById(10);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();
        expect(data1?.author?.id).toBeTruthy();

        if (!data1?.author?.id) return;
        const path = GraphQLPaths.Post.update;

        const updatePost: TPostInput = {
            slug: '__test__',
            pageTitle: data1.pageTitle,
            title: data1.title,
            mainImage: data1.mainImage,
            published: data1.published,
            isEnabled: data1.isEnabled,
            authorId: data1?.author?.id,
            delta: data1?.delta,
            content: data1.content
        }

        await server.executeOperation({
            query: gql`
              mutation testUpdatePost($id: Int!, $data: UpdatePost!) {
                  ${path}(id: $id, data: $data) {
                      ...PostFragment
                  }
              }
              ${crwClient?.PostFragment}
          `,
            variables: {
                id: 10,
                data: updatePost,
            }
        });
        const data2 = await getPostById(10);

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test__').toBeTruthy();
    });


    it(`createPost`, async () => {
        const data1: TPost = await getPostById(10);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();
        expect(data1?.author?.id).toBeTruthy();

        if (!data1?.author?.id) return;
        const path = GraphQLPaths.Post.create;

        const createPost: TPostInput = {
            slug: '__test2__',
            pageTitle: data1.pageTitle,
            title: data1.title,
            mainImage: data1.mainImage,
            published: data1.published,
            isEnabled: data1.isEnabled,
            authorId: data1?.author?.id,
            delta: data1?.delta,
            content: data1.content
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreatePost($data: CreatePost!) {
                  ${path}(data: $data) {
                      ...PostFragment
                  }
              }
              ${crwClient?.PostFragment}
          `,
            variables: {
                data: createPost,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        expect(!Array.isArray(success)).toBeTruthy();

        const data2 = await getPostBySlug('__test2__');

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test2__').toBeTruthy();
    });


    it(`deletePost`, async () => {
        const data1: TPost = await getPostById(11);
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();
        expect(data1?.author?.id).toBeTruthy();

        if (!data1?.author?.id) return;
        const path = GraphQLPaths.Post.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeletePost($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 11,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(!Array.isArray(success)).toBeTruthy();
        expect(success === true).toBeTruthy();

        const data2 = await getPostById(11);

        expect(!data2?.id).toBeTruthy();
        expect(!data2?.slug).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #15
Source File: product-category.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Product category resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('product-category');
        crwClient = getGraphQLClient();
    });

    it(`getProductCategories`, async () => {
        const path = GraphQLPaths.ProductCategory.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetProducts($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...ProductCategoryFragment
                      }
                  }
              }
              ${crwClient?.ProductCategoryFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                    pageSize: 10
                } as TPagedParams<TProductCategory>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length === 10).toBeTruthy();
        expect(data.pagedMeta.pageSize === 10).toBeTruthy();
    });

    const getProductCategoryById = async (id: number) => {
        const path = GraphQLPaths.ProductCategory.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetProductCategoryById($id: Int!) {
                ${path}(id: $id) {
                    ...ProductCategoryFragment
                }
            }
            ${crwClient?.ProductCategoryFragment}
            `,
            variables: {
                id
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getProductCategoryById`, async () => {
        const data = await getProductCategoryById(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    const getProductCategoryBySlug = async (slug: string) => {
        const path = GraphQLPaths.ProductCategory.getOneBySlug;
        const res = await server.executeOperation({
            query: gql`
            query testGetProductCategoryBySlug($slug: String!) {
                ${path}(slug: $slug) {
                    ...ProductCategoryFragment
                }
            }
            ${crwClient?.ProductCategoryFragment}
            `,
            variables: {
                slug
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getProductCategoryBySlug`, async () => {
        const data = await getProductCategoryBySlug('1');
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }
        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    it(`updateProductCategory`, async () => {
        const data1: TProductCategory = await getProductCategoryById(2);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.ProductCategory.update;

        const updateProduct: TProductCategoryInput = {
            slug: '__test__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            mainImage: data1.mainImage,
            isEnabled: data1.isEnabled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateProductCategory($id: Int!, $data: UpdateProductCategory!) {
                  ${path}(id: $id, data: $data) {
                      ...ProductCategoryFragment
                  }
              }
              ${crwClient?.ProductCategoryFragment}
          `,
            variables: {
                id: 2,
                data: updateProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getProductCategoryById(2);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test__').toBeTruthy();
    });


    it(`createProductCategory`, async () => {
        const data1: TProductCategory = await getProductCategoryById(2);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.ProductCategory.create;

        const createProduct: TProductCategoryInput = {
            slug: '__test3__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            mainImage: data1.mainImage,
            isEnabled: data1.isEnabled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreatePost($data: CreateProductCategory!) {
                  ${path}(data: $data) {
                      ...ProductCategoryFragment
                  }
              }
              ${crwClient?.ProductCategoryFragment}
          `,
            variables: {
                data: createProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getProductCategoryBySlug('__test3__');
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test3__').toBeTruthy();
    });


    it(`deleteProductCategory`, async () => {
        const data1: TProductCategory = await getProductCategoryById(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();
        const path = GraphQLPaths.ProductCategory.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteProductCategory($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 3,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', JSON.stringify(success, null, 2))
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getProductCategoryById(3);

        expect(!data2?.id).toBeTruthy();
        expect(!data2?.slug).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #16
Source File: product-review.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Product-review resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('product-review');
        crwClient = getGraphQLClient();
    });

    it(`getProductReviews`, async () => {
        const path = GraphQLPaths.ProductReview.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetProducts($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...ProductReviewFragment
                      }
                  }
              }
              ${crwClient?.ProductReviewFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                    pageSize: 10
                } as TPagedParams<TProductReview>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length === 10).toBeTruthy();
        expect(data.pagedMeta.pageSize === 10).toBeTruthy();
    });

    const getProductReview = async (productReviewId: number) => {
        const path = GraphQLPaths.ProductReview.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetProductById($id: Int!) {
                ${path}(id: $id) {
                    ...ProductReviewFragment
                }
            }
            ${crwClient?.ProductReviewFragment}
            `,
            variables: {
                id: productReviewId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getProductReview`, async () => {
        const data = await getProductReview(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });

    it(`updateProductReview`, async () => {
        const data1: TProductReview = await getProductReview(1);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.ProductReview.update;

        const updateProduct: TProductReviewInput = {
            title: '__test__',
            productId: data1.productId,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateProduct($id: Int!, $data: ProductReviewInput!) {
                  ${path}(id: $id, data: $data) {
                      ...ProductReviewFragment
                  }
              }
              ${crwClient?.ProductReviewFragment}
          `,
            variables: {
                id: 1,
                data: updateProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getProductReview(1);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.title).toBeTruthy();
        expect(data2.title === '__test__').toBeTruthy();
    });


    it(`createProductReview`, async () => {
        const data1: TProductReview = await getProductReview(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.ProductReview.create;

        const createProduct: TProductReviewInput = {
            title: '__test3__',
            productId: data1.productId,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreatePost($data: ProductReviewInput!) {
                  ${path}(data: $data) {
                      ...ProductReviewFragment
                  }
              }
              ${crwClient?.ProductReviewFragment}
          `,
            variables: {
                data: createProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(ProductReviewRepository).findOne({
            where: {
                title: '__test3__'
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.title).toBeTruthy();
        expect(data2?.title === '__test3__').toBeTruthy();
    });


    it(`deleteProduct`, async () => {
        const data1: TProductReview = await getProductReview(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.ProductReview.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteProduct($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getProductReview(4);

        expect(!data2?.id).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #17
Source File: product.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Product resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('product');
        crwClient = getGraphQLClient();
    });

    it(`getProducts`, async () => {
        const path = GraphQLPaths.Product.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetProducts($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...ProductFragment
                      }
                  }
              }
              ${crwClient?.ProductFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                    pageSize: 10
                } as TPagedParams<TProduct>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length === 10).toBeTruthy();
        expect(data.pagedMeta.pageSize === 10).toBeTruthy();
    });

    const getProductById = async (productId: number) => {
        const path = GraphQLPaths.Product.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetProductById($productId: Int!) {
                ${path}(id: $productId) {
                    ...ProductFragment
                }
            }
            ${crwClient?.ProductFragment}
            `,
            variables: {
                productId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getProductById`, async () => {
        const data = await getProductById(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    const getProductBySlug = async (slug: string) => {
        const path = GraphQLPaths.Product.getOneBySlug;
        const res = await server.executeOperation({
            query: gql`
            query testGetProductBySlug($slug: String!) {
                ${path}(slug: $slug) {
                    ...ProductFragment
                }
            }
            ${crwClient?.ProductFragment}
            `,
            variables: {
                slug
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getProductBySlug`, async () => {
        const data = await getProductBySlug('1');
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }
        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
        expect(data.slug).toBeTruthy();
    });

    it(`updateProduct`, async () => {
        const data1: TProduct = await getProductById(2);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.Product.update;

        const updateProduct: TProductInput = {
            slug: '__test__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            mainImage: data1.mainImage,
            isEnabled: data1.isEnabled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateProduct($id: Int!, $data: UpdateProduct!) {
                  ${path}(id: $id, data: $data) {
                      ...ProductFragment
                  }
              }
              ${crwClient?.ProductFragment}
          `,
            variables: {
                id: 2,
                data: updateProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getProductById(2);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test__').toBeTruthy();
    });


    it(`createProduct`, async () => {
        const data1: TProduct = await getProductById(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();

        const path = GraphQLPaths.Product.create;

        const createProduct: TProductInput = {
            slug: '__test3__',
            name: data1.name,
            pageTitle: data1.pageTitle,
            mainImage: data1.mainImage,
            isEnabled: data1.isEnabled,
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreatePost($data: CreateProduct!) {
                  ${path}(data: $data) {
                      ...ProductFragment
                  }
              }
              ${crwClient?.ProductFragment}
          `,
            variables: {
                data: createProduct,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getProductBySlug('__test3__');
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.slug).toBeTruthy();
        expect(data2.slug === '__test3__').toBeTruthy();
    });


    it(`deleteProduct`, async () => {
        const data1: TProduct = await getProductById(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        expect(data1.slug).toBeTruthy();
        const path = GraphQLPaths.Product.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteProduct($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getProductById(4);

        expect(!data2?.id).toBeTruthy();
        expect(!data2?.slug).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #18
Source File: tag.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('Tag resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('tag');
        crwClient = getGraphQLClient();
    });

    it(`getTags`, async () => {
        const path = GraphQLPaths.Tag.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetTags($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...TagFragment
                      }
                  }
              }
              ${crwClient?.TagFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                } as TPagedParams<TTag>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length).toBeTruthy();
        expect(data.pagedMeta.pageSize).toBeTruthy();
    });

    const getTag = async (tagId: number): Promise<TTag> => {
        const path = GraphQLPaths.Tag.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetTagById($id: Int!) {
                ${path}(id: $id) {
                    ...TagFragment
                }
            }
            ${crwClient?.TagFragment}
            `,
            variables: {
                id: tagId
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getTag`, async () => {
        const data = await getTag(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });

    it(`updateTag`, async () => {
        const data1 = await getTag(1);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Tag.update;

        const inputData: TTagInput = {
            name: '__test__',
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateTag($id: Int!, $data: InputTag!) {
                  ${path}(id: $id, data: $data) {
                      ...TagFragment
                  }
              }
              ${crwClient?.TagFragment}
          `,
            variables: {
                id: 1,
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getTag(1);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.name).toEqual(inputData.name);
    });


    it(`createTag`, async () => {
        const data1: TTag = await getTag(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.Tag.create;

        const inputData: TTagInput = {
            name: '__test2__',
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateTag($data: InputTag!) {
                  ${path}(data: $data) {
                      ...TagFragment
                  }
              }
              ${crwClient?.TagFragment}
          `,
            variables: {
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(TagRepository).findOne({
            where: {
                name: inputData.name
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.name).toEqual(inputData.name);
    });


    it(`deleteTag`, async () => {
        const data1 = await getTag(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.Tag.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteTag($id: Int!) {
                    ${path}(id: $id)
                }
          `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getTag(4);

        expect(!data2?.id).toBeTruthy();
    });


    afterAll(async () => {
        await tearDownResolver(server);
    });
});
Example #19
Source File: user.resolver.spec.ts    From Cromwell with MIT License 4 votes vote down vote up
describe('User resolver', () => {
    let server: ApolloServer;
    let crwClient: TCGraphQLClient | undefined;

    beforeAll(async () => {
        server = await setupResolver('user');
        crwClient = getGraphQLClient();
    });

    afterAll(async () => {
        await tearDownResolver(server);
    });

    it(`getUsers`, async () => {
        const path = GraphQLPaths.User.getMany;
        const res = await server.executeOperation({
            query: gql`
              query testGetUsers($pagedParams: PagedParamsInput!) {
                  ${path}(pagedParams: $pagedParams) {
                      pagedMeta {
                          ...PagedMetaFragment
                      }
                      elements {
                          ...UserFragment
                      }
                  }
              }
              ${crwClient?.UserFragment}
              ${crwClient?.PagedMetaFragment}
          `,
            variables: {
                pagedParams: {
                    pageNumber: 1,
                } as TPagedParams<TUser>
            }
        });
        const data = crwClient?.returnData(res, path);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.elements.length).toBeTruthy();
        expect(data.pagedMeta.pageSize).toBeTruthy();
    });

    const getUser = async (id: number): Promise<TUser> => {
        const path = GraphQLPaths.User.getOneById;
        const res = await server.executeOperation({
            query: gql`
            query testGetUserById($id: Int!) {
                ${path}(id: $id) {
                    ...UserFragment
                }
            }
            ${crwClient?.UserFragment}
            `,
            variables: {
                id
            }
        });
        const data = crwClient?.returnData(res, path);
        return data;
    }

    it(`getUser`, async () => {
        const data = await getUser(1);
        if (Array.isArray(data)) {
            console.error('data error', data)
            expect(!Array.isArray(data)).toBeTruthy();
        }

        expect(data).toBeTruthy();
        expect(data.id).toBeTruthy();
    });

    it(`updateUser`, async () => {
        const data1 = await getUser(1);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.User.update;

        const inputData: TUpdateUser = {
            fullName: '__test__',
            email: '[email protected]',
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testUpdateUser($id: Int!, $data: UpdateUser!) {
                  ${path}(id: $id, data: $data) {
                      ...UserFragment
                  }
              }
              ${crwClient?.UserFragment}
          `,
            variables: {
                id: 1,
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        const data2 = await getUser(1);
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }

        expect(data2).toBeTruthy();
        expect(data2.id).toBeTruthy();
        expect(data2.email).toEqual(inputData.email);
    });


    it(`createUser`, async () => {
        const data1: TUser = await getUser(3);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();

        const path = GraphQLPaths.User.create;

        const inputData: TCreateUser = {
            fullName: '__test2__',
            email: '[email protected]',
            password: '__test2__',
        }

        const res = await server.executeOperation({
            query: gql`
              mutation testCreateUser($data: CreateUser!) {
                  ${path}(data: $data) {
                      ...UserFragment
                  }
              }
              ${crwClient?.UserFragment}
          `,
            variables: {
                data: inputData,
            }
        });
        const success = crwClient?.returnData(res, path);
        expect(success).toBeTruthy();
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }

        const data2 = await getCustomRepository(UserRepository).findOne({
            where: {
                email: inputData.email
            }
        });
        if (Array.isArray(data2)) {
            console.error('data error', data2)
            expect(!Array.isArray(data2)).toBeTruthy();
        }
        expect(data2).toBeTruthy();
        expect(data2?.id).toBeTruthy();
        expect(data2?.email).toEqual(inputData.email);
    });


    it(`deleteUser`, async () => {
        const data1 = await getUser(4);
        if (Array.isArray(data1)) {
            console.error('data error', data1)
            expect(!Array.isArray(data1)).toBeTruthy();
        }
        expect(data1).toBeTruthy();
        expect(data1.id).toBeTruthy();
        const path = GraphQLPaths.User.delete;

        const res = await server.executeOperation({
            query: gql`
                mutation testDeleteUser($id: Int!) {
                    ${path}(id: $id)
                }
            `,
            variables: {
                id: 4,
            }
        });
        const success = crwClient?.returnData(res, path);
        if (Array.isArray(success)) {
            console.error('res error', success)
            expect(!Array.isArray(success)).toBeTruthy();
        }
        expect(success === true).toBeTruthy();

        const data2 = await getUser(4);
        expect(!data2?.id).toBeTruthy();
    });
});
Example #20
Source File: typedefs.ts    From Nishan with MIT License 4 votes vote down vote up
NotionGraphqlTypedefs = gql`
	scalar JSONObject

	union TParent = Page | Space

	union TPage = Page | CollectionViewPage

	union TCollectionBlock = CollectionViewPage | CollectionView

	union TBlock = CollectionViewPage | CollectionView | Page

	interface Block {
		type: String!
		id: String!
		parent: TParent!
		space: Space!
		last_edited_by: NotionUser!
		created_by: NotionUser!
	}

	type NotionUser {
		email: String!
		family_name: String!
		given_name: String!
		id: String!
		onboarding_completed: Boolean!
		profile_photo: String!
		version: Int!
	}

	type Space {
		id: String!
		name: String!
		pages: [TPage!]
		last_edited_by: NotionUser!
		created_by: NotionUser!
	}

	type View {
		id: String!
		name: String!
	}

	type CollectionViewPage implements Block {
		id: String!
		collection: Collection!
		parent: TParent!
		type: String!
		space: Space!
		last_edited_by: NotionUser!
		created_by: NotionUser!
		views: [View!]!
	}

	type CollectionView implements Block {
		id: String!
		type: String!
		collection: Collection!
		parent: TParent!
		space: Space!
		last_edited_by: NotionUser!
		created_by: NotionUser!
		views: [View!]!
	}

	type PageProperties {
		title: String!
	}

	type Page implements Block {
		properties: PageProperties!
		id: String!
		type: String!
		parent: TParent!
		space: Space!
		last_edited_by: NotionUser!
		created_by: NotionUser!
		contents: [TBlock!]!
	}

	type Collection {
		id: String!
		name: String!
		schema: JSONObject!
		parent: TCollectionBlock!
		templates: [Page!]!
		rows: [Page!]!
	}

	type Query {
		page(id: ID!): Page
		block(id: ID!): TBlock
		space(id: ID!): Space
	}
`
Example #21
Source File: module.test.ts    From backstage with Apache License 2.0 4 votes vote down vote up
describe('Catalog Module', () => {
  const worker = setupServer();
  const mockCatalogBaseUrl = 'http://im.mock';
  const mockConfig = new ConfigReader({
    backend: {
      baseUrl: mockCatalogBaseUrl,
    },
  });

  const createMockApplication = (module: Module) => {
    const application = createApplication({
      modules: [module],
      schemaBuilder(input) {
        return makeExecutableSchema({
          ...input,
          inheritResolversFromInterfaces: true,
        });
      },
    });

    return application;
  };

  setupRequestMockHandlers(worker);

  describe('Default Entity', () => {
    beforeEach(() => {
      const mockResponse: ReaderEntity[] = [
        {
          apiVersion: 'something',
          kind: 'Component',
          metadata: {
            annotations: {},
            etag: '123',
            labels: {},
            name: 'Ben',
            namespace: 'Blames',
            uid: '123',
          },
          spec: {
            type: 'thing',
            lifecycle: 'something',
            owner: 'auser',
          },
        },
      ];

      worker.use(
        rest.get(`${mockCatalogBaseUrl}/api/catalog/entities`, (_, res, ctx) =>
          res(ctx.status(200), ctx.json(mockResponse)),
        ),
      );
    });

    it('should call the catalog client when requesting entities', async () => {
      const app = createMockApplication(
        await createModule({
          config: mockConfig,
          logger: createLogger(),
        }),
      );

      const result = await testkit.execute(app, {
        document: gql`
          query {
            catalog {
              list {
                kind
                apiVersion
                metadata {
                  name
                }
              }
            }
          }
        `,
      });

      const [catalogItem] = result.data?.catalog.list;
      expect(catalogItem.kind).toBe('Component');
      expect(catalogItem.apiVersion).toBe('something');
      expect(catalogItem.metadata.name).toBe('Ben');
    });

    it('Defaults to empty annotations when none are provided', async () => {
      const mockResponse: ReaderEntity[] = [
        {
          apiVersion: 'something',
          kind: 'Component',
          metadata: {
            annotations: null as any,
            etag: '123',
            labels: {},
            name: 'Ben',
            namespace: 'Blames',
            uid: '123',
          },
          spec: {
            type: 'thing',
            lifecycle: 'something',
            owner: 'auser',
          },
        },
      ];
      worker.use(
        rest.get(`${mockCatalogBaseUrl}/api/catalog/entities`, (_, res, ctx) =>
          res(ctx.status(200), ctx.json(mockResponse)),
        ),
      );

      const app = createMockApplication(
        await createModule({
          config: mockConfig,
          logger: createLogger(),
        }),
      );

      const result = await testkit.execute(app, {
        document: gql`
          query {
            catalog {
              list {
                metadata {
                  annotations
                }
              }
            }
          }
        `,
      });

      const [catalogItem] = result.data?.catalog.list;
      expect(catalogItem.metadata.annotations).toEqual({});
    });

    it('Defaults to empty labels when none are provided', async () => {
      const mockResponse: ReaderEntity[] = [
        {
          apiVersion: 'something',
          kind: 'Component',
          metadata: {
            annotations: {},
            etag: '123',
            labels: null as any,
            name: 'Ben',
            namespace: 'Blames',
            uid: '123',
          },
          spec: {
            type: 'thing',
            lifecycle: 'something',
            owner: 'auser',
          },
        },
      ];
      worker.use(
        rest.get(`${mockCatalogBaseUrl}/api/catalog/entities`, (_, res, ctx) =>
          res(ctx.status(200), ctx.json(mockResponse)),
        ),
      );

      const app = createMockApplication(
        await createModule({
          config: mockConfig,
          logger: createLogger(),
        }),
      );

      const result = await testkit.execute(app, {
        document: gql`
          query {
            catalog {
              list {
                metadata {
                  labels
                }
              }
            }
          }
        `,
      });

      const [catalogItem] = result.data?.catalog.list;
      expect(catalogItem.metadata.labels).toEqual({});
    });
    it('Returns the correct record from the annotation dictionary', async () => {
      const mockResponse: ReaderEntity[] = [
        {
          apiVersion: 'something',
          kind: 'Component',
          metadata: {
            annotations: { lob: 'bloben' },
            etag: '123',
            labels: {},
            name: 'Ben',
            namespace: 'Blames',
            uid: '123',
          },
          spec: {
            type: 'thing',
            lifecycle: 'something',
            owner: 'auser',
          },
        },
      ];
      worker.use(
        rest.get(`${mockCatalogBaseUrl}/api/catalog/entities`, (_, res, ctx) =>
          res(ctx.status(200), ctx.json(mockResponse)),
        ),
      );

      const app = createMockApplication(
        await createModule({
          config: mockConfig,
          logger: createLogger(),
        }),
      );

      const result = await testkit.execute(app, {
        document: gql`
          query {
            catalog {
              list {
                metadata {
                  test: annotation(name: "lob")
                }
              }
            }
          }
        `,
      });

      const [catalogItem] = result.data?.catalog.list;
      expect(catalogItem.metadata.test).toEqual('bloben');
    });
    it('Returns the correct record from the labels dictionary', async () => {
      const mockResponse: ReaderEntity[] = [
        {
          apiVersion: 'something',
          kind: 'Component',
          metadata: {
            annotations: {},
            etag: '123',
            labels: { lob2: 'bloben' },
            name: 'Ben',
            namespace: 'Blames',
            uid: '123',
          },
          spec: {
            type: 'thing',
            lifecycle: 'something',
            owner: 'auser',
          },
        },
      ];
      worker.use(
        rest.get(`${mockCatalogBaseUrl}/api/catalog/entities`, (_, res, ctx) =>
          res(ctx.status(200), ctx.json(mockResponse)),
        ),
      );

      const app = createMockApplication(
        await createModule({
          config: mockConfig,
          logger: createLogger(),
        }),
      );

      const result = await testkit.execute(app, {
        document: gql`
          query {
            catalog {
              list {
                metadata {
                  test: label(name: "lob2")
                }
              }
            }
          }
        `,
      });

      const [catalogItem] = result.data?.catalog.list;
      expect(catalogItem.metadata.test).toEqual('bloben');
    });
  });
});