Skip to content

Commit

Permalink
upgrade generator to use orderby multi fields
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmedElywa committed Aug 18, 2020
1 parent 63b76db commit 787a0d3
Show file tree
Hide file tree
Showing 17 changed files with 87 additions and 144 deletions.
2 changes: 1 addition & 1 deletion packages/admin/src/PrismaTable/QueryDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ query findOne${modelName}($where: ${modelName}WhereUniqueInput!) {
return tag`
query findMany${modelName}(
$where: ${modelName}WhereInput
$orderBy: ${modelName}OrderByInput
$orderBy: [${modelName}OrderByInput!]
$cursor: ${modelName}WhereUniqueInput
$skip: Int
$take: Int
Expand Down
8 changes: 5 additions & 3 deletions packages/admin/src/PrismaTable/Table/useFilterAndSort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,19 @@ const handleFilter = (filters: { id: string; value: any }[]) => {
export const useFilterAndSort = (model: string, filter?: any) => {
const initialFilter = filterMemo(model, filter);
const [where, setWhere] = useState<any>();
const [orderBy, setOrderBy] = useState<any>();
const [orderBy, setOrderBy] = useState<any[]>();

const filterHandler = (filters: { id: string; value: any }[]) => {
setWhere(handleFilter(filters));
};

const sortByHandler = (sortBy: { id: string; desc: boolean }[]) => {
if (sortBy.length > 0) {
const newOrderBy: { [key: string]: 'asc' | 'desc' } = {};
const newOrderBy: { [key: string]: 'asc' | 'desc' }[] = [];
sortBy.forEach((item) => {
newOrderBy[item.id.split('.')[0]] = item.desc ? 'desc' : 'asc';
newOrderBy.push({
[item.id.split('.')[0]]: item.desc ? 'desc' : 'asc',
});
});
setOrderBy(newOrderBy);
} else if (orderBy) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"private": true,
"dependencies": {
"@apollo/client": "3.x",
"@paljs/admin": "1.1.11",
"@paljs/admin": "1.1.12",
"@paljs/ui": "1.x",
"@paljs/icons": "1.x",
"babel-plugin-styled-components": "1.x",
Expand Down
2 changes: 1 addition & 1 deletion packages/create/examples/full-stack-nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"@apollo/react-ssr": "4.x",
"@nexus/schema": "0.x",
"@paljs/nexus": "1.1.9",
"@paljs/admin": "1.1.11",
"@paljs/admin": "1.1.12",
"@paljs/ui": "1.x",
"@paljs/icons": "1.x",
"@prisma/client": "2.x",
Expand Down
146 changes: 32 additions & 114 deletions packages/create/examples/full-stack-nextjs/src/Api/client.tsx
Original file line number Diff line number Diff line change
@@ -1,130 +1,48 @@
import Head from 'next/head'
import * as React from 'react'
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client'
/* eslint-disable @typescript-eslint/no-var-requires */
import { ApolloClient, InMemoryCache } from '@apollo/client'
import { useMemo } from 'react'

let apolloClient: any = null
let apolloClient: any

function createIsomorphLink() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { HttpLink } = require('@apollo/client')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
if (typeof window === 'undefined') {
const { SchemaLink } = require('@apollo/client/link/schema')
const { schema } = require('./nexusSchema')
return new SchemaLink({ schema })
} else {
const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}

function createApolloClient(initialState = {}) {
const ssrMode = typeof window === 'undefined'
const cache = new InMemoryCache().restore(initialState)

function createApolloClient() {
return new ApolloClient({
ssrMode,
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(),
cache,
cache: new InMemoryCache(),
})
}

function initApolloClient(initialState?: any) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (typeof window === 'undefined') {
return createApolloClient(initialState)
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient()

// Reuse client on the client-side
if (!apolloClient) {
apolloClient = createApolloClient(initialState)
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState)
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient

return apolloClient
return _apolloClient
}

/**
* Creates and provides the apolloContext
* to a next.js PageTree. Use it by wrapping
* your PageComponent via HOC pattern.
* @param {Function|Class} PageComponent
* @param {Object} [config]
* @param {Boolean} [config.ssr=true]
*/

export function withApollo(PageComponent: any, { ssr = true } = {}) {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }: any) => {
const client = apolloClient || initApolloClient(apolloState)
return (
<ApolloProvider client={client}>
<PageComponent {...pageProps} />
</ApolloProvider>
)
}

// Set the correct displayName in development
if (process.env.NODE_ENV !== 'production') {
const displayName = PageComponent.displayName || PageComponent.name || 'Component'

if (displayName === 'App') {
console.warn('This withApollo HOC only works with PageComponents.')
}

WithApollo.displayName = `withApollo(${displayName})`
}

if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async (ctx: any) => {
const { AppTree } = ctx

// Initialize ApolloClient, add it to the ctx object so
// we can use it in `PageComponent.getInitialProp`.
const apolloClient = (ctx.apolloClient = initApolloClient())

// Run wrapped getInitialProps methods
let pageProps = {}
if (PageComponent.getInitialProps) {
pageProps = await PageComponent.getInitialProps(ctx)
}

// Only on the server:
if (typeof window === 'undefined') {
// When redirecting, the response is finished.
// No point in continuing to render
if (ctx.res && ctx.res.finished) {
return pageProps
}

// Only if ssr is enabled
if (ssr) {
try {
// Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr')
await getDataFromTree(
<AppTree
pageProps={{
...pageProps,
apolloClient,
}}
/>,
)
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
// Handle them in components via the data.error prop:
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error)
}

// getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually
Head.rewind()
}
}

// Extract query data from the Apollo store
const apolloState = apolloClient.cache.extract()
return {
...pageProps,
apolloState,
}
}
}

return WithApollo
export function useApollo(initialState: any) {
const store = useMemo(() => initializeApollo(initialState), [initialState])
return store
}
16 changes: 10 additions & 6 deletions packages/create/examples/full-stack-nextjs/src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
import Head from 'next/head';
import { AppProps } from 'next/app';
import * as React from 'react';
import { withApollo } from 'Api/client';
import { NextPage } from 'next';
import Layout from 'Layouts/Admin';
import { ApolloProvider } from '@apollo/client';
import { useApollo } from 'Api/client';

import 'react-quill/dist/quill.snow.css';
import 'react-datepicker/dist/react-datepicker.css';

const MyApp: NextPage<AppProps> = ({ Component, pageProps }) => {
const apolloClient = useApollo(pageProps.initialApolloState);
return (
<>
<Head>
<title>Prisma Admin</title>
<title>Job Dashboard</title>
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
</Head>
<Layout>
<Component {...pageProps} />
</Layout>
<ApolloProvider client={apolloClient}>
<Layout>
<Component {...pageProps} />
</Layout>
</ApolloProvider>
</>
);
};

export default withApollo(MyApp);
export default MyApp;
4 changes: 2 additions & 2 deletions packages/generator/src/admin/createGraphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ ${
? `
query findMany${model.name}(
$where: ${model.name}WhereInput
$orderBy: ${model.name}OrderByInput
$orderBy: [${model.name}OrderByInput!]
$cursor: ${model.name}WhereUniqueInput
$skip: Int
$take: Int
Expand All @@ -89,7 +89,7 @@ ${
? `
query findMany${model.name}Count(
$where: ${model.name}WhereInput
$orderBy: ${model.name}OrderByInput
$orderBy: [${model.name}OrderByInput!]
$cursor: ${model.name}WhereUniqueInput
$skip: Int
$take: Int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function createQueriesAndMutations(
operations.queries.type += `
findMany${name}(
where: ${name}WhereInput
orderBy: ${name}OrderByInput
orderBy: [${name}OrderByInput!]
cursor: ${name}WhereUniqueInput
skip: Int
take: Int
Expand All @@ -45,7 +45,7 @@ export function createQueriesAndMutations(
operations.queries.type += `
findMany${name}Count(
where: ${name}WhereInput
orderBy: ${name}OrderByInput
orderBy: [${name}OrderByInput!]
cursor: ${name}WhereUniqueInput
skip: Int
take: Int
Expand All @@ -58,7 +58,13 @@ export function createQueriesAndMutations(

if (!exclude.includes('aggregate')) {
operations.queries.type += `
aggregate${name}: Aggregate${name}`;
aggregate${name}(
where: ${name}WhereInput
orderBy: [${name}OrderByInput!]
cursor: ${name}WhereUniqueInput
skip: Int
take: Int
): Aggregate${name}`;
operations.queries.resolver += `
aggregate${name}: (_parent, args, { injector }: ModuleContext) => {
return injector.get(PrismaProvider).${model}.aggregate(args);
Expand Down
11 changes: 9 additions & 2 deletions packages/generator/src/nexus/templates/aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@ schema.extendType({
const staticData = `('aggregate#{Model}', {
type: 'Aggregate#{Model}',
nullable: true,
resolve(_parent, _args, { prisma, select }) {
return prisma.#{model}.aggregate(select) as any
args: {
where: '#{Model}WhereInput',
orderBy: #{schema}arg({ type: '#{Model}OrderByInput', list: true }),,
cursor: '#{Model}WhereUniqueInput',
skip: 'Int',
take: 'Int',
},
resolve(_parent, args, { prisma, select }) {
return prisma.#{model}.aggregate({...args, ...select}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/createOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ const staticData = `('createOne#{Model}', {
return prisma.#{model}.create({
data,
...select,
})
}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/deleteOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,6 @@ const staticData = `('deleteOne#{Model}', {
return prisma.#{model}.delete({
where,
...select,
})
}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/findCount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const staticData = `('findMany#{Model}Count', {
type: 'Int',
args: {
where: '#{Model}WhereInput',
orderBy: '#{Model}OrderByInput',
orderBy: #{schema}arg({ type: '#{Model}OrderByInput', list: true }),,
cursor: '#{Model}WhereUniqueInput',
skip: 'Int',
take: 'Int',
Expand Down
4 changes: 2 additions & 2 deletions packages/generator/src/nexus/templates/findMany.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const staticData = `('findMany#{Model}', {
list: true,
args: {
where: '#{Model}WhereInput',
orderBy: '#{Model}OrderByInput',
orderBy: #{schema}arg({ type: '#{Model}OrderByInput', list: true }),,
cursor: '#{Model}WhereUniqueInput',
skip: 'Int',
take: 'Int',
Expand All @@ -32,6 +32,6 @@ const staticData = `('findMany#{Model}', {
return prisma.#{model}.findMany({
...args,
...select,
})
}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/findOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ const staticData = `('findOne#{Model}', {
return prisma.#{model}.findOne({
where,
...select,
})
}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/updateOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ const staticData = `('updateOne#{Model}', {
where,
data,
...select,
})
}) as any
},
})`;
2 changes: 1 addition & 1 deletion packages/generator/src/nexus/templates/upsertOne.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ const staticData = `('upsertOne#{Model}', {
return prisma.#{model}.upsert({
...args,
...select,
})
}) as any
},
})`;
Loading

0 comments on commit 787a0d3

Please sign in to comment.