Skip to content

Commit

Permalink
Merge pull request #6 from Abusayid693/post-query
Browse files Browse the repository at this point in the history
post entity updates and fixes
  • Loading branch information
Abusayid693 authored May 18, 2022
2 parents 8407828 + 274d61c commit 6e2f8c9
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 30 deletions.
2 changes: 1 addition & 1 deletion client-ui/codegen.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
overwrite: true
schema: "http://localhost:4000/graphql"
documents: "graphql/**/*.graphql"
documents: "services/graphql/**/*.graphql"
generates:
generated/graphql.tsx:
plugins:
Expand Down
2 changes: 1 addition & 1 deletion client-ui/components/DashboardSideBar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const Index: React.FC<{
h={'100vh'}
position={'relative'}
>
<VStack marginBottom="10vh" marginTop={'5vh'}>
<VStack marginBottom="5vh" marginTop={'5vh'}>
<ThemeToggle />
</VStack>
<VStack marginBottom="70vh">
Expand Down
87 changes: 76 additions & 11 deletions client-ui/generated/graphql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ export type Scalars = {
Float: number;
};

export type EatherUser = {
__typename?: 'EatherUser';
createdAt: Scalars['String'];
email: Scalars['String'];
id: Scalars['Float'];
updatedAt: Scalars['String'];
username: Scalars['String'];
};

export type FieldError = {
__typename?: 'FieldError';
field: Scalars['String'];
Expand Down Expand Up @@ -65,7 +74,7 @@ export type Post = {

export type Query = {
__typename?: 'Query';
Me?: Maybe<User>;
Me?: Maybe<EatherUser>;
hello: Scalars['String'];
post?: Maybe<Post>;
posts?: Maybe<Array<Post>>;
Expand All @@ -79,19 +88,15 @@ export type QueryPostArgs = {
id: Scalars['Float'];
};

export type User = {
__typename?: 'User';
createdAt: Scalars['String'];
id: Scalars['Float'];
updatedAt: Scalars['String'];
username: Scalars['String'];
export type QueryPostsArgs = {
limit?: InputMaybe<Scalars['Int']>;
};

export type UserResponse = {
__typename?: 'UserResponse';
errors?: Maybe<Array<FieldError>>;
token?: Maybe<Scalars['String']>;
user?: Maybe<User>;
user?: Maybe<EatherUser>;
};

export type UsernamePasswordInput = {
Expand All @@ -113,7 +118,7 @@ export type LoginMutation = {
| Array<{__typename?: 'FieldError'; field: string; message: string}>
| null
| undefined;
user?: {__typename?: 'User'; username: string} | null | undefined;
user?: {__typename?: 'EatherUser'; username: string} | null | undefined;
};
};

Expand All @@ -131,19 +136,31 @@ export type RegisterMutation = {
| Array<{__typename?: 'FieldError'; field: string; message: string}>
| null
| undefined;
user?: {__typename?: 'User'; username: string} | null | undefined;
user?: {__typename?: 'EatherUser'; username: string} | null | undefined;
};
};

export type AuthTestingQueryVariables = Exact<{[key: string]: never}>;

export type AuthTestingQuery = {__typename?: 'Query'; hello: string};

export type PostsQueryVariables = Exact<{
limit: Scalars['Int'];
}>;

export type PostsQuery = {
__typename?: 'Query';
posts?: Array<{__typename?: 'Post'; title: string}> | null | undefined;
};

export type SessionCheckQueryVariables = Exact<{[key: string]: never}>;

export type SessionCheckQuery = {
__typename?: 'Query';
Me?: {__typename?: 'User'; id: number; username: string} | null | undefined;
Me?:
| {__typename?: 'EatherUser'; id: number; username: string}
| null
| undefined;
};

export const LoginDocument = gql`
Expand Down Expand Up @@ -309,6 +326,54 @@ export type AuthTestingQueryResult = Apollo.QueryResult<
AuthTestingQuery,
AuthTestingQueryVariables
>;
export const PostsDocument = gql`
query Posts($limit: Int!) {
posts(limit: $limit) {
title
}
}
`;

/**
* __usePostsQuery__
*
* To run a query within a React component, call `usePostsQuery` and pass it any options that fit your needs.
* When your component renders, `usePostsQuery` 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 } = usePostsQuery({
* variables: {
* limit: // value for 'limit'
* },
* });
*/
export function usePostsQuery(
baseOptions: Apollo.QueryHookOptions<PostsQuery, PostsQueryVariables>
) {
const options = {...defaultOptions, ...baseOptions};
return Apollo.useQuery<PostsQuery, PostsQueryVariables>(
PostsDocument,
options
);
}
export function usePostsLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<PostsQuery, PostsQueryVariables>
) {
const options = {...defaultOptions, ...baseOptions};
return Apollo.useLazyQuery<PostsQuery, PostsQueryVariables>(
PostsDocument,
options
);
}
export type PostsQueryHookResult = ReturnType<typeof usePostsQuery>;
export type PostsLazyQueryHookResult = ReturnType<typeof usePostsLazyQuery>;
export type PostsQueryResult = Apollo.QueryResult<
PostsQuery,
PostsQueryVariables
>;
export const SessionCheckDocument = gql`
query SessionCheck {
Me {
Expand Down
11 changes: 10 additions & 1 deletion client-ui/pages/dashboard/saved.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import DashboardSideBar from 'components/DashboardSideBar';
import {usePostsQuery} from 'generated/graphql';
import {useRouter} from 'next/router';
import useAuth from '../../hooks/useAuth';

const Index = () => {
const auth = useAuth();
const router = useRouter();

const {data} = usePostsQuery({
variables: {
limit: 10
}
});

console.log('data : ', data);

// useEffect(() => {
// if (!auth.isAuthenticated() && !auth.loading) router.push('/');
// }, [auth.isAuthenticated(), auth.loading]);
Expand All @@ -14,7 +23,7 @@ const Index = () => {
<>
{auth.isAuthenticated() ? (
<DashboardSideBar activeIndex={1}>
<h1>Please first login</h1>
{data?.posts?.map((item: any) => JSON.stringify(item))}
</DashboardSideBar>
) : (
<h1>Please first login</h1>
Expand Down
5 changes: 5 additions & 0 deletions client-ui/services/graphql/queries/posts.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
query Posts($limit: Int!) {
posts(limit: $limit){
title
}
}
3 changes: 2 additions & 1 deletion db.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const local = {
username: 'rehanchoudhury',
database: 'postgres',
logging: true,
entities: [Post, EatherUser]
entities: [Post, EatherUser],
synchronize: true
};

const dbConfig = !__prod__ ? local : production;
Expand Down
14 changes: 9 additions & 5 deletions entities/Post.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {Field, ObjectType} from 'type-graphql';
import {
Entity,
PrimaryGeneratedColumn,
BaseEntity,
Column,
CreateDateColumn,
UpdateDateColumn,
BaseEntity
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn
} from 'typeorm';
import {Field, ObjectType} from 'type-graphql';

@ObjectType()
@Entity()
Expand All @@ -26,4 +26,8 @@ export class Post extends BaseEntity {
@Field()
@Column()
title!: string;

@Field()
@Column()
creatorId: number;
}
46 changes: 36 additions & 10 deletions resolvers/post.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,54 @@
import {Post} from '../entities/Post';
import {Resolver, Query, Arg, Mutation} from 'type-graphql';
import {
Arg,
Ctx,
Int,
Mutation,
Query,
Resolver,
UseMiddleware
} from 'type-graphql';
import {getConnection} from 'typeorm';
import {MyContext} from '../@types/types';
import {Post} from '../entities/Post';
import {protect} from '../middlewares/protect';

@Resolver()
export class PostResolver {
@Query(() => Post, {nullable: true})
post(
// @Arg("id", ()=> Int) id: number,
@Arg('id') id: number
) {
@UseMiddleware(protect)
post(@Arg('id') id: number) {
return Post.findOne(id);
}

@Query(() => [Post], {nullable: true})
posts(): Promise<Post[]> {
return Post.find();
@UseMiddleware(protect)
async posts(
@Arg('limit', () => Int, {nullable: true}) limit: number,
// @Arg('creatorId', () => Int) creatorId: number,
@Ctx() {req}: MyContext
): Promise<Post[]> {
const query = getConnection()
.getRepository(Post)
.createQueryBuilder()
.where('"creatorId" = :creatorId', {
creatorId: req.user.id
})
.orderBy('"createdAt"', 'DESC');

if (limit) query.take(limit);

return await query.getMany();
}

@Mutation(() => Post)
async createPosts(@Arg('title') title: string) {
const post = Post.create({title}).save();
@UseMiddleware(protect)
async createPosts(@Arg('title') title: string, @Ctx() {req}: MyContext) {
const post = Post.create({title, creatorId: req.user.id}).save();
return post;
}

@Mutation(() => Post, {nullable: true})
@UseMiddleware(protect)
async updatePost(
@Arg('id') id: number,
@Arg('title', () => String, {nullable: true}) title: string
Expand All @@ -43,6 +68,7 @@ export class PostResolver {
}

@Mutation(() => Boolean)
@UseMiddleware(protect)
async deletePost(@Arg('id') id: number) {
try {
await Post.delete({id});
Expand Down

0 comments on commit 6e2f8c9

Please sign in to comment.