Skip to content

Commit

Permalink
feat: set a maximum message length in controller
Browse files Browse the repository at this point in the history
  • Loading branch information
jkklapp committed Jun 6, 2022
1 parent 97190b1 commit c3843cd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
3 changes: 2 additions & 1 deletion backend/.env
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ FB_PARAMS_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FB_PARAMS_TOKEN_URI=https://oauth2.googleapis.com/token
FB_PARAMS_AUTH_PROVIDER_X509_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FB_PARAMS_CLIENT_C509_CERT_URL=https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-j8wbf%40wsne-28b5b.iam.gserviceaccount.com
MAX_NUMBER_POSTS_PER_DAY=10
MAX_NUMBER_POSTS_PER_DAY=10
MAX_MESSAGE_LENGTH=120
13 changes: 12 additions & 1 deletion backend/src/posts/controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('Controller', () => {
s = new Service(collection);
c = new Controller(s);
old_env = process.env;
process.env = { MAX_NUMBER_POSTS_PER_DAY: '5' };
process.env = { MAX_NUMBER_POSTS_PER_DAY: '5', MAX_MESSAGE_LENGTH: '100' };
jest.spyOn(s, 'countAllforUserByDate').mockResolvedValue(0);
});
afterEach(() => {
Expand Down Expand Up @@ -89,5 +89,16 @@ describe('Controller', () => {
).rejects.toThrow();
});
});
describe('when the message is too long', () => {
it('should throw an error', async () => {
await expect(
c.create(
{ user: { user_id: '1234' } },
{ message: 'test'.repeat(100) },
),
).rejects.toThrow();
expect(s.create).not.toHaveBeenCalled();
});
});
});
});
9 changes: 9 additions & 0 deletions backend/src/posts/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class Controller {
): Promise<ResolvedPostDocument> {
const { user } = request;
const { user_id: userId, name: userName } = user;

const last24hours = Date.now() - 86400000;
const numberPostsCreatedToday = await this.service.countAllforUserByDate(
userId,
Expand All @@ -84,6 +85,14 @@ export class Controller {
' posts per day',
);
}

const maxMessageLength = parseInt(process.env.MAX_MESSAGE_LENGTH, 10);
if (post.message.length > maxMessageLength) {
throw new BadRequestException(
'Message is too long. Max length is ' + maxMessageLength,
);
}

return this.service.create(post.message, userId, userName);
}
}

0 comments on commit c3843cd

Please sign in to comment.