Skip to content

Commit

Permalink
feat: resolve author name by user ID
Browse files Browse the repository at this point in the history
  • Loading branch information
jkklapp committed Jun 1, 2022
1 parent fb9d480 commit 1f72db7
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 29 deletions.
10 changes: 6 additions & 4 deletions backend/src/posts/controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Timestamp } from '@google-cloud/firestore';
import { Controller } from './controller';
import { Service } from './service';

Expand All @@ -19,7 +18,8 @@ describe('Controller', () => {
{
message: 'test',
date: 100000,
author: '1234',
userId: '1234',
userName: 'Test',
},
],
nextPageToken: null,
Expand All @@ -40,14 +40,16 @@ describe('Controller', () => {
Promise.resolve({
...post,
date: 100000,
author: '1234',
userId: '1234',
userName: 'Test',
}),
);

expect(await c.create({ user: { user_id: '1234' } }, post)).toEqual({
...post,
date: 100000,
author: '1234',
userId: '1234',
userName: 'Test',
});
});
});
Expand Down
14 changes: 9 additions & 5 deletions backend/src/posts/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import {
Req,
UseGuards,
} from '@nestjs/common';
import { PostDocument, NewPostDocument, PostDocumentResult } from './document';
import {
ResolvedPostDocument,
NewPostDocument,
PostDocumentResult,
} from './document';
import { Service } from './service';
import { FirebaseAuthGuard } from '../firebase/firebase-auth.guard';

Expand All @@ -20,7 +24,7 @@ export class Controller {
@UseGuards(FirebaseAuthGuard)
findAll(
@Query('limit', ParseIntPipe) limit: number,
@Query('startAfter') startAfter?: number,
@Query('startAfter') startAfter?: string,
): Promise<PostDocumentResult> {
return this.service.findAll(limit, startAfter);
}
Expand All @@ -30,8 +34,8 @@ export class Controller {
public create(
@Req() request: any,
@Body() post: NewPostDocument,
): Promise<PostDocument> {
const userId = request.user.user_id;
return this.service.create(post, userId);
): Promise<ResolvedPostDocument> {
const { user } = request;
return this.service.create(post, user);
}
}
18 changes: 11 additions & 7 deletions backend/src/posts/document.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
export class PostDocument {
static collectionName = 'posts';

export class NewPostDocument {
message: string;
date: number;
author: string;
}

export class NewPostDocument {
export class PostDocument extends NewPostDocument {
static collectionName = 'posts';

message: string;
date: number;
userId: string;
}

export class PostDocumentResult {
results: PostDocument[];
results: ResolvedPostDocument[];
nextPageToken?: number;
}

export class ResolvedPostDocument extends PostDocument {
userName: string;
}
33 changes: 25 additions & 8 deletions backend/src/posts/service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Injectable, Inject, Logger } from '@nestjs/common';
import * as dayjs from 'dayjs';
import { CollectionReference, Timestamp } from '@google-cloud/firestore';
import { PostDocument, PostDocumentResult } from './document';
import { PostDocument, PostDocumentResult, ResolvedPostDocument } from './document';
import { getDisplayNameByUserId } from './utils';

@Injectable()
export class Service {
Expand All @@ -12,38 +13,54 @@ export class Service {
private postsCollection: CollectionReference<PostDocument>,
) {}

async findAll(limit, startAfter): Promise<PostDocumentResult> {
async findAll(
limit: number,
startAfter?: string | undefined,
): Promise<PostDocumentResult> {
const _startAfter = startAfter ? parseInt(startAfter, 10) : '';
const noMoreResults = startAfter ? -1 : null;
const snapshot = await this.postsCollection
.orderBy('date', 'desc')
.startAfter(_startAfter)
.limit(limit)
.get();

const posts: PostDocument[] = [];
snapshot.forEach((doc) => {
posts.push(doc.data());
});
const q = await snapshot.query.offset(limit).get();

const noMoreResults = startAfter ? -1 : null;
const resolvedPosts: ResolvedPostDocument[] = [];
for (const p in posts) {
resolvedPosts.push({
...posts[p],
userName: await getDisplayNameByUserId(posts[p].userId),
});
}

const q = await snapshot.query.offset(limit).get();

return {
results: posts.slice(),
results: resolvedPosts.slice(),
nextPageToken: q.empty ? noMoreResults : posts[posts.length - 1].date,
};
}

async create({ message }, userId): Promise<PostDocument> {
async create({ message }, user): Promise<ResolvedPostDocument> {
const t = dayjs(new Date()).valueOf();
const date = Timestamp.fromMillis(t);
const docRef = this.postsCollection.doc(t.toString());
const { userId } = user;
await docRef.set({
message,
date: date.seconds,
author: userId,
userId,
});
const postDoc = await docRef.get();
const post = postDoc.data();
return post;
return {
...post,
userName: user.displayName,
};
}
}
10 changes: 10 additions & 0 deletions backend/src/posts/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as firebase from 'firebase-admin';

export const getDisplayNameByUserId = async (
authorId: string,
): Promise<string> => {
return await firebase
.auth()
.getUser(authorId)
.then(({ displayName }) => displayName);
};
3 changes: 2 additions & 1 deletion frontend/src/components/Dashboard/Posts.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ describe('Posts', () => {
jest.resetAllMocks();
});
it('will render posts', () => {
expect(wrapper.find('p').text()).toContain('Hello World a few seconds ago');
expect(wrapper.find('small').text()).toBe('- a few seconds ago');
expect(wrapper.find('span').text()).toContain('Hello World');
});
it('will render the "Load more" button', () => {
expect(wrapper.find('button').exists()).toBe(true);
Expand Down
13 changes: 9 additions & 4 deletions frontend/src/components/Dashboard/Posts.vue
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
<template>
<div>
<div v-if="!isLoading">
<p
<div
v-for="p in posts"
:key="p.id"
class="relative bg-gray-200 dark:bg-gray-500 text-gray-800 dark:text-gray-100 px-6 pt-10 pb-8 mb-2 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg sm:px-10"
class="bg-gray-200 dark:bg-gray-500 text-gray-800 dark:text-gray-100 px-4 pt-2 pb-2 mb-2 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-lg sm:rounded-lg"
>
{{ p.message }} {{ date(p.date) }}
</p>
<div>
<small>{{ p.userName }} - {{ date(p.date) }}</small>
</div>
<div>
<span>{{ p.message }}</span>
</div>
</div>
<div class="grid flex-wrap place-items-center">
<button
v-if="renderLoadMoreButton"
Expand Down

0 comments on commit 1f72db7

Please sign in to comment.