From 7977b664c1062c7a1934d25cbc2c199cc2982b38 Mon Sep 17 00:00:00 2001 From: Fi1osof Date: Fri, 5 Mar 2021 01:01:12 +0300 Subject: [PATCH] ResourceUnion --- pages/[...path].tsx | 5 + server/nexus/generated/nexus.ts | 34 +++- server/nexus/generated/schema.graphql | 12 +- server/nexus/types/City.ts | 1 + server/nexus/types/Company.ts | 3 +- server/nexus/types/Query/definitions/City.ts | 1 + .../nexus/types/Query/definitions/Resource.ts | 24 ++- server/nexus/types/Query/index.ts | 23 +++ .../Query/resolvers/companiesResolver.ts | 2 + server/nexus/types/Resource.ts | 21 ++- src/gql/city.graphql | 34 ++-- src/gql/company.graphql | 3 +- src/gql/resource.graphql | 26 +++ src/modules/gql/generated/CompanyFields.ts | 4 +- src/modules/gql/generated/cities.ts | 20 +-- src/modules/gql/generated/city.ts | 27 +++ .../gql/generated/helpers/apollo-helpers.ts | 10 +- src/modules/gql/generated/index.ts | 5 +- src/modules/gql/generated/resource.ts | 45 +++++ src/modules/gql/generated/resources.ts | 70 ++++++++ src/modules/gql/generated/schema.json | 106 ++++++++++-- src/modules/gql/generated/types.ts | 10 +- src/pages/Companies/Company/View/index.tsx | 16 +- src/pages/Resource/index.tsx | 157 ++++++++++++++++++ src/pages/Resource/interfaces.ts | 5 + 25 files changed, 585 insertions(+), 79 deletions(-) create mode 100644 pages/[...path].tsx create mode 100644 src/gql/resource.graphql create mode 100644 src/modules/gql/generated/city.ts create mode 100644 src/modules/gql/generated/resource.ts create mode 100644 src/modules/gql/generated/resources.ts create mode 100644 src/pages/Resource/index.tsx create mode 100644 src/pages/Resource/interfaces.ts diff --git a/pages/[...path].tsx b/pages/[...path].tsx new file mode 100644 index 0000000..913ecf2 --- /dev/null +++ b/pages/[...path].tsx @@ -0,0 +1,5 @@ +/** + * Handle all unrouted pages + */ + +export { default } from 'src/pages/Resource' diff --git a/server/nexus/generated/nexus.ts b/server/nexus/generated/nexus.ts index 445a958..c290de1 100644 --- a/server/nexus/generated/nexus.ts +++ b/server/nexus/generated/nexus.ts @@ -277,6 +277,7 @@ export interface NexusGenObjects { id: number // Int! longtitle: string // String! pagetitle: string // String! + template: number // Int! uri?: string | null // String } Company: { @@ -295,6 +296,8 @@ export interface NexusGenObjects { longtitle: string // String! pagetitle: string // String! published: boolean // Boolean! + searchable: boolean // Boolean! + template: number // Int! uri?: string | null // String } Coordinates: { @@ -324,6 +327,7 @@ export interface NexusGenObjects { longtitle: string // String! pagetitle: string // String! published: boolean // Boolean! + searchable: boolean // Boolean! template: number // Int! uri?: string | null // String } @@ -338,9 +342,14 @@ export interface NexusGenObjects { export interface NexusGenInterfaces {} -export interface NexusGenUnions {} +export interface NexusGenUnions { + ResourceUnion: + | NexusGenRootTypes['City'] + | NexusGenRootTypes['Company'] + | NexusGenRootTypes['Resource'] +} -export type NexusGenRootTypes = NexusGenObjects +export type NexusGenRootTypes = NexusGenObjects & NexusGenUnions export type NexusGenAllTypes = NexusGenRootTypes & NexusGenScalars & @@ -357,6 +366,7 @@ export interface NexusGenFieldTypes { id: number // Int! longtitle: string // String! pagetitle: string // String! + template: number // Int! uri: string | null // String } Company: { @@ -381,6 +391,8 @@ export interface NexusGenFieldTypes { pagetitle: string // String! prices: string | null // String published: boolean // Boolean! + searchable: boolean // Boolean! + template: number // Int! uri: string | null // String workTime: string | null // String } @@ -400,7 +412,7 @@ export interface NexusGenFieldTypes { // field return type cities: NexusGenRootTypes['City'][] // [City!]! companies: NexusGenRootTypes['Company'][] // [Company!]! - resources: NexusGenRootTypes['Resource'][] // [Resource!]! + resources: NexusGenRootTypes['ResourceUnion'][] // [ResourceUnion!]! } Resource: { // field return type @@ -416,6 +428,7 @@ export interface NexusGenFieldTypes { longtitle: string // String! pagetitle: string // String! published: boolean // Boolean! + searchable: boolean // Boolean! template: number // Int! uri: string | null // String } @@ -437,6 +450,7 @@ export interface NexusGenFieldTypeNames { id: 'Int' longtitle: 'String' pagetitle: 'String' + template: 'Int' uri: 'String' } Company: { @@ -459,6 +473,8 @@ export interface NexusGenFieldTypeNames { pagetitle: 'String' prices: 'String' published: 'Boolean' + searchable: 'Boolean' + template: 'Int' uri: 'String' workTime: 'String' } @@ -478,7 +494,7 @@ export interface NexusGenFieldTypeNames { // field return type name cities: 'City' companies: 'Company' - resources: 'Resource' + resources: 'ResourceUnion' } Resource: { // field return type name @@ -492,6 +508,7 @@ export interface NexusGenFieldTypeNames { longtitle: 'String' pagetitle: 'String' published: 'Boolean' + searchable: 'Boolean' template: 'Int' uri: 'String' } @@ -524,7 +541,6 @@ export interface NexusGenArgTypes { } resources: { // args - cursor?: NexusGenInputs['bani684_site_contentWhereUniqueInput'] | null // bani684_site_contentWhereUniqueInput orderBy?: NexusGenInputs['bani684_site_contentOrderByInput'][] | null // [bani684_site_contentOrderByInput!] skip?: number | null // Int take?: number | null // Int @@ -533,7 +549,9 @@ export interface NexusGenArgTypes { } } -export interface NexusGenAbstractTypeMembers {} +export interface NexusGenAbstractTypeMembers { + ResourceUnion: 'City' | 'Company' | 'Resource' +} export interface NexusGenTypeInterfaces {} @@ -547,11 +565,11 @@ export type NexusGenInterfaceNames = never export type NexusGenScalarNames = keyof NexusGenScalars -export type NexusGenUnionNames = never +export type NexusGenUnionNames = keyof NexusGenUnions export type NexusGenObjectsUsingAbstractStrategyIsTypeOf = never -export type NexusGenAbstractsUsingStrategyResolveType = never +export type NexusGenAbstractsUsingStrategyResolveType = 'ResourceUnion' export type NexusGenFeaturesConfig = { abstractTypeStrategies: { diff --git a/server/nexus/generated/schema.graphql b/server/nexus/generated/schema.graphql index 3b46a35..bfc0b45 100644 --- a/server/nexus/generated/schema.graphql +++ b/server/nexus/generated/schema.graphql @@ -26,6 +26,7 @@ type City { id: Int! longtitle: String! pagetitle: String! + template: Int! uri: String } @@ -67,6 +68,8 @@ type Company { """ prices: String published: Boolean! + searchable: Boolean! + template: Int! uri: String """ @@ -178,12 +181,11 @@ type Query { Ресурсы """ resources( - cursor: bani684_site_contentWhereUniqueInput orderBy: [bani684_site_contentOrderByInput!] skip: Int take: Int where: bani684_site_contentWhereInput - ): [Resource!]! + ): [ResourceUnion!]! } type Resource { @@ -197,10 +199,16 @@ type Resource { longtitle: String! pagetitle: String! published: Boolean! + searchable: Boolean! template: Int! uri: String } +""" +Компания, Город или иной ресурс +""" +union ResourceUnion = City | Company | Resource + enum SortOrder { asc desc diff --git a/server/nexus/types/City.ts b/server/nexus/types/City.ts index ade46bb..c72446c 100644 --- a/server/nexus/types/City.ts +++ b/server/nexus/types/City.ts @@ -12,6 +12,7 @@ export const City = objectType({ t.nonNull.int('id') t.nonNull.string('pagetitle') t.nonNull.string('longtitle') + t.nonNull.int('template') t.string('uri') t.string('alias') // t.field('coords', { diff --git a/server/nexus/types/Company.ts b/server/nexus/types/Company.ts index 23d549a..01b391d 100644 --- a/server/nexus/types/Company.ts +++ b/server/nexus/types/Company.ts @@ -21,8 +21,9 @@ export const Company = objectType({ t.string('content') t.string('uri') t.string('alias') - // t.nonNull.int("template") + t.nonNull.int('template') t.nonNull.boolean('published') + t.nonNull.boolean('searchable') // t.nonNull.date("publishedon") t.nonNull.int('editedby') t.nonNull.date('editedon') diff --git a/server/nexus/types/Query/definitions/City.ts b/server/nexus/types/Query/definitions/City.ts index 0bac453..758b342 100644 --- a/server/nexus/types/Query/definitions/City.ts +++ b/server/nexus/types/Query/definitions/City.ts @@ -59,6 +59,7 @@ export const cities = (t: ObjectDefinitionBlock<'Query'>) => { // createdon: true, // editedby: true, // editedon: true, + template: true, TemplateVarValues: { select: { id: true, diff --git a/server/nexus/types/Query/definitions/Resource.ts b/server/nexus/types/Query/definitions/Resource.ts index f78c0fd..ddfc04b 100644 --- a/server/nexus/types/Query/definitions/Resource.ts +++ b/server/nexus/types/Query/definitions/Resource.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/camelcase */ /* eslint-disable @typescript-eslint/ban-ts-ignore */ -import { ObjectDefinitionBlock } from 'nexus/dist/core' +import { list, nonNull, ObjectDefinitionBlock } from 'nexus/dist/core' import { Prisma } from '@prisma/client' export const resources = (t: ObjectDefinitionBlock<'Query'>) => { @@ -21,12 +21,20 @@ export const resources = (t: ObjectDefinitionBlock<'Query'>) => { // take: 'Int', // skip: 'Int', // }, - t.crud.bani684SiteContents({ - alias: 'resources', + // t.crud.bani684SiteContents({ + + t.nonNull.list.nonNull.field('resources', { + // alias: 'resources', description: 'Ресурсы', - type: 'Resource', - ordering: true, - filtering: true, + type: 'ResourceUnion', + // ordering: true, + // filtering: true, + args: { + where: 'bani684_site_contentWhereInput', + orderBy: list(nonNull('bani684_site_contentOrderByInput')), + take: 'Int', + skip: 'Int', + }, resolve(_, args, ctx) { const variables = args as Pick< Prisma.bani684_site_contentFindManyArgs, @@ -61,6 +69,7 @@ export const resources = (t: ObjectDefinitionBlock<'Query'>) => { createdby: true, createdon: true, template: true, + searchable: true, // editedby: true, // editedon: true, TemplateVarValues: { @@ -71,6 +80,9 @@ export const resources = (t: ObjectDefinitionBlock<'Query'>) => { value: true, }, }, + content: true, + editedby: true, + editedon: true, }, // orderBy: { // pagetitle: "asc", diff --git a/server/nexus/types/Query/index.ts b/server/nexus/types/Query/index.ts index c815ba2..333967e 100644 --- a/server/nexus/types/Query/index.ts +++ b/server/nexus/types/Query/index.ts @@ -16,6 +16,29 @@ export const Query = objectType({ resources(t) // resourcesCount(t) + // t.nonNull.list.field("resources", { + // type: "ResourceUnion", + // resolve: () => { + + // return []; + // } + // }) + + // t.crud.bani684SiteContents({ + // alias: 'resources', + // type: ResourceUnion, + // ordering: true, + // filtering: true, + // resolve: async (_, _args, ctx) => { + + // // const result = await ctx.prisma.bani684_site_content.count(); + + // // console.log("bani684ModxsiteCompaniess result", result); + + // return []; + // }, + // }) + // t.crud.bani684SiteContents({ // alias: 'resources', // type: 'Resource', diff --git a/server/nexus/types/Query/resolvers/companiesResolver.ts b/server/nexus/types/Query/resolvers/companiesResolver.ts index 411cb0b..871243d 100644 --- a/server/nexus/types/Query/resolvers/companiesResolver.ts +++ b/server/nexus/types/Query/resolvers/companiesResolver.ts @@ -43,6 +43,8 @@ export const companiesResolver: FieldResolver< createdon: true, editedby: true, editedon: true, + template: true, + searchable: true, TemplateVarValues: { select: { id: true, diff --git a/server/nexus/types/Resource.ts b/server/nexus/types/Resource.ts index 4a15836..7599f73 100644 --- a/server/nexus/types/Resource.ts +++ b/server/nexus/types/Resource.ts @@ -1,4 +1,4 @@ -import { objectType } from 'nexus' +import { objectType, unionType } from 'nexus' // alias // city_id @@ -14,6 +14,24 @@ import { objectType } from 'nexus' // mapIcon // image +export const ResourceUnion = unionType({ + name: 'ResourceUnion', + description: 'Компания, Город или иной ресурс', + definition(t) { + t.members('Resource', 'Company', 'City') + }, + // resolveType: (item) => item.name, + resolveType: (item) => { + if (item.template === 26) { + return 'City' + } else if (item.template === 27) { + return 'Company' + } + + return 'Resource' + }, +}) + export const Resource = objectType({ name: 'Resource', // sourceType: { @@ -34,6 +52,7 @@ export const Resource = objectType({ t.nonNull.int('template') t.nonNull.boolean('published') t.nonNull.int('createdby') + t.nonNull.boolean('searchable') // t.nonNull.int("editedby") // t.nonNull.date("editedon") diff --git a/src/gql/city.graphql b/src/gql/city.graphql index 2c6f883..8baca0e 100644 --- a/src/gql/city.graphql +++ b/src/gql/city.graphql @@ -15,20 +15,24 @@ query cities( skip: $skip where: $where ) { - id - pagetitle - longtitle - alias - uri - coords { - lat - lng - zoom - } - # image - # imageFormats { - # marker_thumb - # } - # parent + ...city } } + +fragment city on City { + id + pagetitle + longtitle + alias + uri + coords { + lat + lng + zoom + } + # image + # imageFormats { + # marker_thumb + # } + # parent +} diff --git a/src/gql/company.graphql b/src/gql/company.graphql index 2c5fc09..26ef5ae 100644 --- a/src/gql/company.graphql +++ b/src/gql/company.graphql @@ -115,8 +115,9 @@ fragment CompanyFields on Company { # city_id # city # city_uri - # template + template published + searchable # publishedon # pubdate createdon diff --git a/src/gql/resource.graphql b/src/gql/resource.graphql new file mode 100644 index 0000000..7949c6f --- /dev/null +++ b/src/gql/resource.graphql @@ -0,0 +1,26 @@ +query resources( + $where: bani684_site_contentWhereInput + $orderBy: [bani684_site_contentOrderByInput!] + $take: Int + $skip: Int +) { + resources(where: $where, orderBy: $orderBy, take: $take, skip: $skip) { + ...resource + } +} + +fragment resource on ResourceUnion { + ... on Resource { + id + pagetitle + uri + } + + ... on Company { + ...CompanyFields + } + + ... on City { + ...city + } +} diff --git a/src/modules/gql/generated/CompanyFields.ts b/src/modules/gql/generated/CompanyFields.ts index 2a39055..2d3139d 100644 --- a/src/modules/gql/generated/CompanyFields.ts +++ b/src/modules/gql/generated/CompanyFields.ts @@ -9,7 +9,7 @@ import * as Types from './types'; import { gql } from '@apollo/client'; -export type CompanyFieldsFragment = { __typename?: 'Company', id: number, pagetitle: string, longtitle: string, alias?: Types.Maybe, uri?: Types.Maybe, published: boolean, createdon: globalThis.Date, createdby: number, editedby: number, editedon: globalThis.Date, image?: Types.Maybe, address?: Types.Maybe, workTime?: Types.Maybe, prices?: Types.Maybe, coords?: Types.Maybe<{ __typename?: 'Coordinates', lat: number, lng: number }>, gallery: Array<{ __typename?: 'GalleryImage', image: string, title: string, description: string }> }; +export type CompanyFieldsFragment = { __typename?: 'Company', id: number, pagetitle: string, longtitle: string, alias?: Types.Maybe, uri?: Types.Maybe, template: number, published: boolean, searchable: boolean, createdon: globalThis.Date, createdby: number, editedby: number, editedon: globalThis.Date, image?: Types.Maybe, address?: Types.Maybe, workTime?: Types.Maybe, prices?: Types.Maybe, coords?: Types.Maybe<{ __typename?: 'Coordinates', lat: number, lng: number }>, gallery: Array<{ __typename?: 'GalleryImage', image: string, title: string, description: string }> }; export const CompanyFieldsFragmentDoc = gql` fragment CompanyFields on Company { @@ -18,7 +18,9 @@ export const CompanyFieldsFragmentDoc = gql` longtitle alias uri + template published + searchable createdon createdby editedby diff --git a/src/modules/gql/generated/cities.ts b/src/modules/gql/generated/cities.ts index 4914497..65be31f 100644 --- a/src/modules/gql/generated/cities.ts +++ b/src/modules/gql/generated/cities.ts @@ -8,7 +8,9 @@ import * as Types from './types'; +import { CityFragment } from './city'; import { gql } from '@apollo/client'; +import { CityFragmentDoc } from './city'; import * as Apollo from '@apollo/client'; export type CitiesQueryVariables = Types.Exact<{ take?: Types.Maybe; @@ -17,25 +19,19 @@ export type CitiesQueryVariables = Types.Exact<{ }>; -export type CitiesQuery = { __typename?: 'Query', cities: Array<{ __typename?: 'City', id: number, pagetitle: string, longtitle: string, alias?: Types.Maybe, uri?: Types.Maybe, coords?: Types.Maybe<{ __typename?: 'Coordinates', lat: number, lng: number, zoom?: Types.Maybe }> }> }; +export type CitiesQuery = { __typename?: 'Query', cities: Array<( + { __typename?: 'City' } + & CityFragment + )> }; export const CitiesDocument = gql` query cities($take: Int, $skip: Int, $where: bani684_site_contentWhereInput) { cities: cities(take: $take, skip: $skip, where: $where) { - id - pagetitle - longtitle - alias - uri - coords { - lat - lng - zoom - } + ...city } } - `; + ${CityFragmentDoc}`; /** * __useCitiesQuery__ diff --git a/src/modules/gql/generated/city.ts b/src/modules/gql/generated/city.ts new file mode 100644 index 0000000..30543ec --- /dev/null +++ b/src/modules/gql/generated/city.ts @@ -0,0 +1,27 @@ +/* eslint-disable */ + +/** +* ФАЙЛ ГЕНЕРИРУЕТСЯ АВТОМАТИЧЕСКИ, ПРАВИТЬ ЕГО НЕ НУЖНО +* Команда для генерирования этого файла: "yarn generate:types" +*/ + + +import * as Types from './types'; + +import { gql } from '@apollo/client'; +export type CityFragment = { __typename?: 'City', id: number, pagetitle: string, longtitle: string, alias?: Types.Maybe, uri?: Types.Maybe, coords?: Types.Maybe<{ __typename?: 'Coordinates', lat: number, lng: number, zoom?: Types.Maybe }> }; + +export const CityFragmentDoc = gql` + fragment city on City { + id + pagetitle + longtitle + alias + uri + coords { + lat + lng + zoom + } +} + `; \ No newline at end of file diff --git a/src/modules/gql/generated/helpers/apollo-helpers.ts b/src/modules/gql/generated/helpers/apollo-helpers.ts index ec77fa4..4cddd0f 100644 --- a/src/modules/gql/generated/helpers/apollo-helpers.ts +++ b/src/modules/gql/generated/helpers/apollo-helpers.ts @@ -1,5 +1,5 @@ import { FieldPolicy, FieldReadFunction, TypePolicies, TypePolicy } from '@apollo/client/cache'; -export type CityKeySpecifier = ('TemplateVarValues' | 'alias' | 'coords' | 'id' | 'longtitle' | 'pagetitle' | 'uri' | CityKeySpecifier)[]; +export type CityKeySpecifier = ('TemplateVarValues' | 'alias' | 'coords' | 'id' | 'longtitle' | 'pagetitle' | 'template' | 'uri' | CityKeySpecifier)[]; export type CityFieldPolicy = { TemplateVarValues?: FieldPolicy | FieldReadFunction, alias?: FieldPolicy | FieldReadFunction, @@ -7,9 +7,10 @@ export type CityFieldPolicy = { id?: FieldPolicy | FieldReadFunction, longtitle?: FieldPolicy | FieldReadFunction, pagetitle?: FieldPolicy | FieldReadFunction, + template?: FieldPolicy | FieldReadFunction, uri?: FieldPolicy | FieldReadFunction }; -export type CompanyKeySpecifier = ('TemplateVarValues' | 'address' | 'addressComments' | 'alias' | 'content' | 'coords' | 'createdby' | 'createdon' | 'description' | 'editedby' | 'editedon' | 'gallery' | 'id' | 'image' | 'longtitle' | 'pagetitle' | 'prices' | 'published' | 'uri' | 'workTime' | CompanyKeySpecifier)[]; +export type CompanyKeySpecifier = ('TemplateVarValues' | 'address' | 'addressComments' | 'alias' | 'content' | 'coords' | 'createdby' | 'createdon' | 'description' | 'editedby' | 'editedon' | 'gallery' | 'id' | 'image' | 'longtitle' | 'pagetitle' | 'prices' | 'published' | 'searchable' | 'template' | 'uri' | 'workTime' | CompanyKeySpecifier)[]; export type CompanyFieldPolicy = { TemplateVarValues?: FieldPolicy | FieldReadFunction, address?: FieldPolicy | FieldReadFunction, @@ -29,6 +30,8 @@ export type CompanyFieldPolicy = { pagetitle?: FieldPolicy | FieldReadFunction, prices?: FieldPolicy | FieldReadFunction, published?: FieldPolicy | FieldReadFunction, + searchable?: FieldPolicy | FieldReadFunction, + template?: FieldPolicy | FieldReadFunction, uri?: FieldPolicy | FieldReadFunction, workTime?: FieldPolicy | FieldReadFunction }; @@ -50,7 +53,7 @@ export type QueryFieldPolicy = { companies?: FieldPolicy | FieldReadFunction, resources?: FieldPolicy | FieldReadFunction }; -export type ResourceKeySpecifier = ('TemplateVarValues' | 'alias' | 'content' | 'createdby' | 'createdon' | 'description' | 'id' | 'longtitle' | 'pagetitle' | 'published' | 'template' | 'uri' | ResourceKeySpecifier)[]; +export type ResourceKeySpecifier = ('TemplateVarValues' | 'alias' | 'content' | 'createdby' | 'createdon' | 'description' | 'id' | 'longtitle' | 'pagetitle' | 'published' | 'searchable' | 'template' | 'uri' | ResourceKeySpecifier)[]; export type ResourceFieldPolicy = { TemplateVarValues?: FieldPolicy | FieldReadFunction, alias?: FieldPolicy | FieldReadFunction, @@ -62,6 +65,7 @@ export type ResourceFieldPolicy = { longtitle?: FieldPolicy | FieldReadFunction, pagetitle?: FieldPolicy | FieldReadFunction, published?: FieldPolicy | FieldReadFunction, + searchable?: FieldPolicy | FieldReadFunction, template?: FieldPolicy | FieldReadFunction, uri?: FieldPolicy | FieldReadFunction }; diff --git a/src/modules/gql/generated/index.ts b/src/modules/gql/generated/index.ts index 6f4aa78..61dcc44 100644 --- a/src/modules/gql/generated/index.ts +++ b/src/modules/gql/generated/index.ts @@ -2,4 +2,7 @@ export * from './CompanyFields'; export * from './Company_'; export * from './ListCompany'; export * from './cities'; -export * from './companies';export * from './types'; +export * from './city'; +export * from './companies'; +export * from './resource'; +export * from './resources';export * from './types'; diff --git a/src/modules/gql/generated/resource.ts b/src/modules/gql/generated/resource.ts new file mode 100644 index 0000000..6c13015 --- /dev/null +++ b/src/modules/gql/generated/resource.ts @@ -0,0 +1,45 @@ +/* eslint-disable */ + +/** +* ФАЙЛ ГЕНЕРИРУЕТСЯ АВТОМАТИЧЕСКИ, ПРАВИТЬ ЕГО НЕ НУЖНО +* Команда для генерирования этого файла: "yarn generate:types" +*/ + + +import * as Types from './types'; + +import { CompanyFieldsFragment } from './CompanyFields'; +import { CityFragment } from './city'; +import { gql } from '@apollo/client'; +import { CompanyFieldsFragmentDoc } from './CompanyFields'; +import { CityFragmentDoc } from './city'; +export type ResourceCityFragment = ( + { __typename?: 'City' } + & CityFragment +); + +export type ResourceCompanyFragment = ( + { __typename?: 'Company' } + & CompanyFieldsFragment +); + +export type ResourceResourceFragment = { __typename?: 'Resource', id: number, pagetitle: string, uri?: Types.Maybe }; + +export type ResourceFragment = ResourceCityFragment | ResourceCompanyFragment | ResourceResourceFragment; + +export const ResourceFragmentDoc = gql` + fragment resource on ResourceUnion { + ... on Resource { + id + pagetitle + uri + } + ... on Company { + ...CompanyFields + } + ... on City { + ...city + } +} + ${CompanyFieldsFragmentDoc} +${CityFragmentDoc}`; \ No newline at end of file diff --git a/src/modules/gql/generated/resources.ts b/src/modules/gql/generated/resources.ts new file mode 100644 index 0000000..496b7de --- /dev/null +++ b/src/modules/gql/generated/resources.ts @@ -0,0 +1,70 @@ +/* eslint-disable */ + +/** +* ФАЙЛ ГЕНЕРИРУЕТСЯ АВТОМАТИЧЕСКИ, ПРАВИТЬ ЕГО НЕ НУЖНО +* Команда для генерирования этого файла: "yarn generate:types" +*/ + + +import * as Types from './types'; + +import { ResourceCityFragment, ResourceCompanyFragment, ResourceResourceFragment } from './resource'; +import { gql } from '@apollo/client'; +import { ResourceFragmentDoc } from './resource'; +import * as Apollo from '@apollo/client'; +export type ResourcesQueryVariables = Types.Exact<{ + where?: Types.Maybe; + orderBy?: Types.Maybe | Types.Bani684SiteContentOrderByInput>; + take?: Types.Maybe; + skip?: Types.Maybe; +}>; + + +export type ResourcesQuery = { __typename?: 'Query', resources: Array<( + { __typename?: 'City' } + & ResourceCityFragment + ) | ( + { __typename?: 'Company' } + & ResourceCompanyFragment + ) | ( + { __typename?: 'Resource' } + & ResourceResourceFragment + )> }; + + +export const ResourcesDocument = gql` + query resources($where: bani684_site_contentWhereInput, $orderBy: [bani684_site_contentOrderByInput!], $take: Int, $skip: Int) { + resources(where: $where, orderBy: $orderBy, take: $take, skip: $skip) { + ...resource + } +} + ${ResourceFragmentDoc}`; + +/** + * __useResourcesQuery__ + * + * To run a query within a React component, call `useResourcesQuery` and pass it any options that fit your needs. + * When your component renders, `useResourcesQuery` returns an object from Apollo Client that contains loading, error, and data properties + * you can use to render your UI. + * + * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options; + * + * @example + * const { data, loading, error } = useResourcesQuery({ + * variables: { + * where: // value for 'where' + * orderBy: // value for 'orderBy' + * take: // value for 'take' + * skip: // value for 'skip' + * }, + * }); + */ +export function useResourcesQuery(baseOptions?: Apollo.QueryHookOptions) { + return Apollo.useQuery(ResourcesDocument, baseOptions); + } +export function useResourcesLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions) { + return Apollo.useLazyQuery(ResourcesDocument, baseOptions); + } +export type ResourcesQueryHookResult = ReturnType; +export type ResourcesLazyQueryHookResult = ReturnType; +export type ResourcesQueryResult = Apollo.QueryResult; \ No newline at end of file diff --git a/src/modules/gql/generated/schema.json b/src/modules/gql/generated/schema.json index 195f81e..a7d1e7f 100644 --- a/src/modules/gql/generated/schema.json +++ b/src/modules/gql/generated/schema.json @@ -195,6 +195,22 @@ "isDeprecated": false, "deprecationReason": null }, + { + "name": "template", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "Int", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, { "name": "uri", "description": null, @@ -510,6 +526,38 @@ "isDeprecated": false, "deprecationReason": null }, + { + "name": "searchable", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "Boolean", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "template", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "Int", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, { "name": "uri", "description": null, @@ -1468,18 +1516,6 @@ "name": "resources", "description": "Ресурсы", "args": [ - { - "name": "cursor", - "description": null, - "type": { - "kind": "INPUT_OBJECT", - "name": "bani684_site_contentWhereUniqueInput", - "ofType": null - }, - "defaultValue": null, - "isDeprecated": false, - "deprecationReason": null - }, { "name": "orderBy", "description": null, @@ -1547,8 +1583,8 @@ "kind": "NON_NULL", "name": null, "ofType": { - "kind": "OBJECT", - "name": "Resource", + "kind": "UNION", + "name": "ResourceUnion", "ofType": null } } @@ -1724,6 +1760,22 @@ "isDeprecated": false, "deprecationReason": null }, + { + "name": "searchable", + "description": null, + "args": [], + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "SCALAR", + "name": "Boolean", + "ofType": null + } + }, + "isDeprecated": false, + "deprecationReason": null + }, { "name": "template", "description": null, @@ -1758,6 +1810,32 @@ "enumValues": null, "possibleTypes": null }, + { + "kind": "UNION", + "name": "ResourceUnion", + "description": "Компания, Город или иной ресурс", + "fields": null, + "inputFields": null, + "interfaces": null, + "enumValues": null, + "possibleTypes": [ + { + "kind": "OBJECT", + "name": "City", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "Company", + "ofType": null + }, + { + "kind": "OBJECT", + "name": "Resource", + "ofType": null + } + ] + }, { "kind": "ENUM", "name": "SortOrder", diff --git a/src/modules/gql/generated/types.ts b/src/modules/gql/generated/types.ts index e260ebe..0ea170b 100644 --- a/src/modules/gql/generated/types.ts +++ b/src/modules/gql/generated/types.ts @@ -42,6 +42,7 @@ export interface City { id: Scalars['Int']; longtitle: Scalars['String']; pagetitle: Scalars['String']; + template: Scalars['Int']; uri?: Maybe; } @@ -70,6 +71,8 @@ export interface Company { /** Цены */ prices?: Maybe; published: Scalars['Boolean']; + searchable: Scalars['Boolean']; + template: Scalars['Int']; uri?: Maybe; /** Рабочее время */ workTime?: Maybe; @@ -153,7 +156,7 @@ export interface Query { /** Компании */ companies: Array; /** Ресурсы */ - resources: Array; + resources: Array; } @@ -176,7 +179,6 @@ export type QueryCompaniesArgs = { export type QueryResourcesArgs = { - cursor?: Maybe; orderBy?: Maybe>; skip?: Maybe; take?: Maybe; @@ -195,10 +197,14 @@ export interface Resource { longtitle: Scalars['String']; pagetitle: Scalars['String']; published: Scalars['Boolean']; + searchable: Scalars['Boolean']; template: Scalars['Int']; uri?: Maybe; } +/** Компания, Город или иной ресурс */ +export type ResourceUnion = City | Company | Resource; + export enum SortOrder { ASC = 'asc', DESC = 'desc' diff --git a/src/pages/Companies/Company/View/index.tsx b/src/pages/Companies/Company/View/index.tsx index 03372b6..acaeedd 100644 --- a/src/pages/Companies/Company/View/index.tsx +++ b/src/pages/Companies/Company/View/index.tsx @@ -354,9 +354,7 @@ const CompanyView: React.FC = ({ company: item }) => { - {inEditMode ? // } // (errors && errors.address) || 'Укажите подробный адрес' // helperText={ // error={errors && errors.address ? true : false} // label="Адрес" // this.onFocus('address')} // /> @@ -387,9 +385,7 @@ const CompanyView: React.FC = ({ company: item }) => { '' )} - {inEditMode ? // onChange={this.onChange} // value={metro || ''} // name="metro" // helperText="Укажите ближайшие станции метро через запятую" // label="Метро" // this.onFocus('metro')} - // /> + {inEditMode ? // /> // onFocus={() => this.onFocus('metro')} // onChange={this.onChange} // value={metro || ''} // name="metro" // helperText="Укажите ближайшие станции метро через запятую" // label="Метро" // = ({ company: item }) => { '' )} - {inEditMode ? // onChange={this.onChange} // value={phones || ''} // name="phones" // helperText="Можно указать несколько телефонов через запятую" // label="Телефон" // this.onFocus('phones')} - // /> + {inEditMode ? // /> // onFocus={() => this.onFocus('phones')} // onChange={this.onChange} // value={phones || ''} // name="phones" // helperText="Можно указать несколько телефонов через запятую" // label="Телефон" // = ({ company: item }) => { '' )} - {inEditMode ? // value={site || ''} // name="site" // helperText="Если адрес начинается с https, обязательно укажите вместе с ним, например, https://ваш_сайт/" // label="Сайт" // this.onFocus('site')} + {inEditMode ? // onFocus={() => this.onFocus('site')} // onChange={this.onChange} // value={site || ''} // name="site" // helperText="Если адрес начинается с https, обязательно укажите вместе с ним, например, https://ваш_сайт/" // label="Сайт" // null : site ? ( { + const uri = new URL( + router.asPath || '', + global.location?.origin || 'http://localhost' + ) + + const pathname = decodeURI(uri.pathname).replace(/^\/+/, '') + + const variables: ResourcesQueryVariables = { + take: 1, + where: { + deleted: { + equals: false, + }, + published: { + equals: true, + }, + OR: [ + { + uri: { + equals: pathname, + }, + }, + { + uri: { + equals: pathname + '/', + }, + }, + ], + }, + } + + return variables +} + +const ResourcePage: Page = () => { + const router = useRouter() + + const variables = useMemo(() => getResourceVariables(router), [router]) + + const response = useResourcesQuery({ + variables, + onError: console.error, + }) + + const object = response.data?.resources[0] + + return useMemo(() => { + if (!object || !object.__typename) { + return null + } + + if (object.__typename === 'Company') { + // + + return + } else { + throw new Error('Unknown Resource type') + } + }, [object]) +} + +ResourcePage.getInitialProps = async (context) => { + const { apolloClient } = context + + const variables = getResourceVariables(context) + + // console.log('ResourcePage variables', variables); + + const queryResult = await apolloClient.query({ + query: ResourcesDocument, + + /** + * Важно, чтобы все переменные запроса серверные и фронтовые совпадали, + * иначе при рендеринге не будут получены данные из кеша и рендер будет пустой. + */ + variables, + }) + + /** + * Получаем первый попавшийся документ по запрошенному УРЛу + */ + const object = queryResult.data.resources[0] + + // let type: ResourcePageProps["type"] + + // if (object) { + + // /** + // * Определяем тип ресурса по шаблону + // */ + // switch (object.template) { + + // case 27: + + // type = "company"; + // break; + + // } + + // } + + // console.log('ResourcePage object', object); + + // switch (object?.type) { + // case ResourceType.TOPIC: + // case ResourceType.COMMENT: + // break + + // case ResourceType.BLOG: + // case ResourceType.PERSONALBLOG: + // await blogGetInitialProps(context, object) + + // break + + // default: + // return { + // statusCode: 404, + // } + // } + + return { + queryResult, + statusCode: + !object || !object.__typename || !['Company'].includes(object.__typename) + ? 404 + : undefined, + // type, + } +} + +export default ResourcePage diff --git a/src/pages/Resource/interfaces.ts b/src/pages/Resource/interfaces.ts new file mode 100644 index 0000000..12fc073 --- /dev/null +++ b/src/pages/Resource/interfaces.ts @@ -0,0 +1,5 @@ +import { PageProps } from '../_App/interfaces' + +export type ResourcePageProps = PageProps & { + // type: "company" | undefined +}