Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor user collection #302

Merged
merged 8 commits into from
Dec 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions src/__tests__/acceptance/user.acceptance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ describe('UserApplication', function () {
});

delete updatedUser.id;
delete updatedUser.username;

await client
.patch(`/users/${persistedUser.id}`)
Expand All @@ -179,17 +180,13 @@ describe('UserApplication', function () {
expect(result).to.containEql(updatedUser);
});

it('returns 422 when updating a user username more than once', async () => {
it('returns 422 when updating a username', async () => {
const updatedUser: Partial<User> = givenUser({
username: 'abdulhakim',
});

delete updatedUser.id;

await client
.patch(`/users/${persistedUser.id}`)
.send(updatedUser)
.expect(204);
await client
.patch(`/users/${persistedUser.id}`)
.send(updatedUser)
Expand All @@ -200,6 +197,7 @@ describe('UserApplication', function () {
const updatedUser: Partial<User> = givenUser();

delete updatedUser.id;
delete updatedUser.username;

return client.patch('/users/99999').send(updatedUser).expect(404);
});
Expand Down
2 changes: 2 additions & 0 deletions src/__tests__/helpers/given-instances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export function givenUser(user?: Partial<User>) {
{
id: '0x06cc7ed22ebd12ccc28fb9c0d14a5c4420a331d89a5fef48b915e8449ee61859',
name: 'Abdul Hakim',
username: 'abdulhakim',
},
user,
);
Expand All @@ -83,6 +84,7 @@ export async function givenMultipleUserInstances(
givenUserInstance(userRepository, {
id: '0x06cc7ed22ebd12ccc28fb9c0d14a5c4420a331d89a5fef48b915e8449ee61863',
name: 'irman',
username: 'irman',
}),
]);
}
Expand Down
1 change: 1 addition & 0 deletions src/__tests__/unit/user.controller.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ describe('UserControllers', () => {
givenUser({
id: '0x06cc7ed22ebd12ccc28fb9c0d14a5c4420a331d89a5fef48b915e8449ee61861',
name: 'husni',
username: 'husni',
bio: 'Hello, my name is husni!',
}),
] as User[];
Expand Down
29 changes: 0 additions & 29 deletions src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ import {Filter, FilterExcludingWhere, repository} from '@loopback/repository';
import {
get,
getModelSchemaRef,
HttpErrors,
param,
patch,
post,
requestBody,
response,
} from '@loopback/rest';
import {BcryptHasher} from '../services/authentication/hash.password.service';
import {ActivityLogType, ReferenceType} from '../enums';
import {DeletedDocument, PaginationInterceptor} from '../interceptors';
import {User} from '../models';
import {UserRepository} from '../repositories';
Expand Down Expand Up @@ -120,31 +118,4 @@ export class UserController {
): Promise<void> {
await this.userRepository.updateById(id, user);
}

@post('/users/{id}/skip-username')
@response(200, {
description: 'Skip username success',
})
async skipUsername(@param.path.string('id') id: string): Promise<void> {
const found = await this.userRepository.activityLogs(id).find({
where: {
type: ActivityLogType.SKIPUSERNAME,
},
});

if (found.length >= 1) {
throw new HttpErrors.UnprocessableEntity(
'You have already skip updating username',
);
}

await this.userRepository.activityLogs(id).create({
type: ActivityLogType.SKIPUSERNAME,
userId: id,
referenceType: ReferenceType.USER,
referenceId: id,
});

return;
}
}
3 changes: 2 additions & 1 deletion src/enums/activity-log-type.enum.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
export enum ActivityLogType {
CREATEUSERNAME = 'username',
SKIPUSERNAME = 'skip_new_user_username',
NEWUSER = 'new_user',
UPLOADPROFILEPICTURE = 'upload_profile_picture',
FILLBIO = 'fill_in_bio',
UPLOADBANNER = 'upload_banner',
SKIPUSERNAME = 'skip_new_user_username',
SENDTIP = 'send_tip',
IMPORTPOST = 'import_post',
CLAIMSOCIAL = 'claim_social_media',
Expand Down
77 changes: 18 additions & 59 deletions src/interceptors/initial-creation.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,56 +148,22 @@ export class InitialCreationInterceptor implements Provider<Interceptor> {
): Promise<void> {
switch (className) {
case ControllerType.USER: {
const newUser = new User(invocationCtx.args[0]);
const user = await this.userRepository.findOne({
where: {
id: newUser.id,
},
});
const {id, username} = invocationCtx.args[0];

this.validateUsername(username);

let user = await this.userRepository.findOne({where: {id}});

if (user)
throw new HttpErrors.UnprocessableEntity('User already exist!');

const flag = true;
const name = newUser.name.substring(0, 22);
const usernameBase = newUser.name
.replace(/[^A-Za-z0-9]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.split(' ')[0]
.toLowerCase();

let username = usernameBase.substring(0, 16);

while (flag) {
const found = await this.userRepository.findOne({
where: {
username: username,
},
});

let count = 2;

if (found) {
let newUsername = usernameBase + this.generateRandomCharacter();
newUsername = newUsername.substring(0, 16);

if (newUsername === found.username) {
username =
newUsername.substring(0, 16 - count) +
this.generateRandomCharacter();
username = username.substring(0, 16);
count++;
} else {
username = newUsername;
}
} else break;
}
user = new User(invocationCtx.args[0]);

const name = user.name.substring(0, 22);

newUser.name = name;
newUser.username = username;
user.name = name;

invocationCtx.args[0] = newUser;
invocationCtx.args[0] = user;
return;
}

Expand Down Expand Up @@ -238,6 +204,13 @@ export class InitialCreationInterceptor implements Provider<Interceptor> {
await this.friendService.defaultFriend(result.id);
await this.currencyService.defaultCurrency(result.id);
await this.currencyService.defaultAcalaTips(result.id); // TODO: removed default acala tips
await this.activityLogService.createLog(
ActivityLogType.NEWUSER,
result.id,
result.id,
ReferenceType.USER,
);

return result;
}

Expand Down Expand Up @@ -332,14 +305,7 @@ export class InitialCreationInterceptor implements Provider<Interceptor> {
user: Partial<User>,
): Promise<void> {
if (user.username) {
this.validateUsername(user.username);

await this.activityLogService.createLog(
ActivityLogType.CREATEUSERNAME,
userId,
userId,
ReferenceType.USER,
);
throw new HttpErrors.UnprocessableEntity('Cannot update username');
}

if (user.profilePictureURL) {
Expand Down Expand Up @@ -391,13 +357,6 @@ export class InitialCreationInterceptor implements Provider<Interceptor> {
throw new HttpErrors.UnprocessableEntity('Cannot added comment anymore');
}

generateRandomCharacter(): string {
const randomCharOne = Math.random().toString(36).substring(2);
const randomCharTwo = Math.random().toString(36).substring(2);

return '.' + randomCharOne + randomCharTwo;
}

validateUsername(username: string): void {
if (
username[username.length - 1] === '.' ||
Expand Down
6 changes: 0 additions & 6 deletions src/migrations/0.0.0.migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,6 @@ export class MigrationScript000 implements MigrationScript {
user.createdAt = new Date().toString();
user.updatedAt = new Date().toString();

user.username =
user.username ??
user.name.replace(/\s+/g, '').toLowerCase() +
'.' +
Math.random().toString(36).substr(2, 9);

return this.userRepository.create(user);
}),
);
Expand Down
4 changes: 2 additions & 2 deletions src/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class User extends Entity {

@property({
type: 'string',
required: false,
required: true,
index: {
unique: true,
},
Expand Down Expand Up @@ -135,7 +135,7 @@ export class User extends Entity {
@property({
type: 'string',
required: false,
default: DefaultCurrencyType.AUSD,
default: DefaultCurrencyType.MYRIA,
})
defaultCurrency?: string;

Expand Down
8 changes: 0 additions & 8 deletions src/services/activity-log.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {BindingScope, injectable} from '@loopback/core';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {ActivityLogType, ReferenceType} from '../enums';
import {ActivityLog} from '../models';
import {ActivityLogRepository, LeaderBoardRepository} from '../repositories';
Expand Down Expand Up @@ -34,15 +33,8 @@ export class ActivityLogService {
referenceType,
});

if (count >= 1 && type === ActivityLogType.CREATEUSERNAME) {
throw new HttpErrors.UnprocessableEntity(
'You can only updated username once',
);
}

await this.activityLogRepository.create(activityLog);

if (type === ActivityLogType.CREATEUSERNAME) return;
if (count === 0) {
// count activity
const found = await this.leaderboardRepository.findOne({
Expand Down