-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #70 from ansopedia/be-60-create-profile-api
Add PUT /profile API to handle upsert profile request
- Loading branch information
Showing
17 changed files
with
278 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { | ||
expectBadRequestResponseForValidationError, | ||
expectLoginSuccess, | ||
expectProfileData, | ||
expectUnauthorizedResponseForInvalidAuthorizationHeader, | ||
expectUnauthorizedResponseForInvalidToken, | ||
expectUnauthorizedResponseForMissingAuthorizationHeader, | ||
login, | ||
upSertProfileData, | ||
} from '@/utils/test'; | ||
import { defaultUsers } from '@/constants'; | ||
import { CreateProfileData } from '../profile.validation'; | ||
|
||
const profileData: CreateProfileData = { avatar: 'http://avatar.com', bio: 'bio', phoneNumber: 'phoneNumber' }; | ||
|
||
describe('Profile Service', () => { | ||
let authorizationHeader: string; | ||
let loggedInUserId: string; | ||
|
||
beforeAll(async () => { | ||
const loginResponse = await login(defaultUsers); | ||
expectLoginSuccess(loginResponse); | ||
loggedInUserId = loginResponse.body.userId; | ||
authorizationHeader = `Bearer ${loginResponse.header['authorization']}`; | ||
}); | ||
|
||
describe('upSertProfileData', () => { | ||
it('should throw error if access token is not provided', async () => { | ||
const response = await upSertProfileData({}, ''); | ||
expectUnauthorizedResponseForMissingAuthorizationHeader(response); | ||
}); | ||
|
||
it('should return 401 for invalid authorization header', async () => { | ||
const response = await upSertProfileData({}, 'invalid'); | ||
expectUnauthorizedResponseForInvalidAuthorizationHeader(response); | ||
}); | ||
|
||
it('should throw an error if invalid access token is provided', async () => { | ||
const response = await upSertProfileData({}, 'Bearer invalid-access-token'); | ||
expectUnauthorizedResponseForInvalidToken(response); | ||
}); | ||
|
||
it('should throw error if body is not provided', async () => { | ||
const response = await upSertProfileData({}, authorizationHeader); | ||
expectBadRequestResponseForValidationError(response); | ||
}); | ||
|
||
it('should update profile data', async () => { | ||
const response = await upSertProfileData(profileData, authorizationHeader); | ||
expectProfileData(response, { userId: loggedInUserId, ...profileData }); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export * from './profile.service'; | ||
export * from './profile.validation'; | ||
export * from './profile.constant'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export const success = { | ||
PROFILE_UPDATED_SUCCESSFULLY: 'Profile updated successfully', | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { sendResponse } from '@/utils'; | ||
import { NextFunction, Request, Response } from 'express'; | ||
import { ProfileService } from './profile.service'; | ||
import { success } from './profile.constant'; | ||
|
||
export class ProfileController { | ||
static upSertProfile = async (req: Request, res: Response, next: NextFunction) => { | ||
try { | ||
const profile = await new ProfileService().upSertProfileData({ | ||
userId: req.body.loggedInUser.userId, | ||
...req.body, | ||
}); | ||
sendResponse({ | ||
response: res, | ||
message: success.PROFILE_UPDATED_SUCCESSFULLY, | ||
payload: profile, | ||
statusCode: 200, | ||
}); | ||
} catch (error) { | ||
next(error); | ||
} | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import { ProfileDataModel } from './profile.modal'; | ||
import { ProfileData } from './profile.validation'; | ||
|
||
interface IProfileDataDal { | ||
upSertProfileData(payload: ProfileData): Promise<ProfileData>; | ||
} | ||
|
||
export class ProfileDataDAL implements IProfileDataDal { | ||
async upSertProfileData(payload: ProfileData): Promise<ProfileData> { | ||
return await ProfileDataModel.findOneAndUpdate({ userId: payload.userId }, payload, { | ||
upsert: true, | ||
new: true, | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { ProfileData } from './profile.validation'; | ||
|
||
export const ProfileDto = (profile: ProfileData) => ({ | ||
getProfile: () => { | ||
return { | ||
userId: profile.userId, | ||
avatar: profile.avatar, | ||
bio: profile.bio, | ||
address: profile.address, | ||
phoneNumber: profile.phoneNumber, | ||
socialLinks: profile.socialLinks, | ||
}; | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { model, Schema, Types } from 'mongoose'; | ||
import { ProfileData } from './profile.validation'; | ||
|
||
const ProfileData = new Schema<ProfileData>( | ||
{ | ||
userId: { | ||
type: String, | ||
required: true, | ||
validate: { | ||
validator: (v: string) => Types.ObjectId.isValid(v), | ||
message: 'userId must be a valid MongoDB ObjectId string', | ||
}, | ||
ref: 'User', | ||
}, | ||
avatar: { | ||
type: String, | ||
trim: true, | ||
}, | ||
bio: { | ||
type: String, | ||
trim: true, | ||
maxlength: 500, | ||
}, | ||
address: { | ||
type: { | ||
street: { type: String }, | ||
city: { type: String }, | ||
country: { type: String }, | ||
zipCode: { type: String }, | ||
}, | ||
}, | ||
phoneNumber: { | ||
type: String, | ||
trim: true, | ||
}, | ||
socialLinks: { | ||
type: { | ||
twitter: { type: String }, | ||
linkedin: { type: String }, | ||
github: { type: String }, | ||
}, | ||
}, | ||
}, | ||
{ timestamps: true }, | ||
); | ||
|
||
export const ProfileDataModel = model<ProfileData>('Profile', ProfileData); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import { Router } from 'express'; | ||
import { validateAccessToken } from '@/middlewares'; | ||
import { ProfileController } from './profile.controller'; | ||
|
||
const router = Router(); | ||
|
||
router.put('/profile', validateAccessToken, ProfileController.upSertProfile); | ||
|
||
export { router as profileRoutes }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { ProfileDataDAL } from './profile.dal'; | ||
import { ProfileDto } from './profile.dto'; | ||
import { ProfileData, validateProfileSchema } from './profile.validation'; | ||
|
||
export class ProfileService { | ||
private profileDataDal: ProfileDataDAL; | ||
|
||
constructor() { | ||
this.profileDataDal = new ProfileDataDAL(); | ||
} | ||
|
||
upSertProfileData = async (payload: ProfileData) => { | ||
const profileData = validateProfileSchema(payload); | ||
|
||
const updateProfileData = await this.profileDataDal.upSertProfileData(profileData); | ||
return ProfileDto(updateProfileData).getProfile(); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { z } from 'zod'; | ||
import { objectIdSchema } from '@/utils'; | ||
|
||
export const profileSchema = z.object({ | ||
userId: objectIdSchema, | ||
avatar: z.string().url().optional(), | ||
bio: z.string().max(500).optional(), | ||
address: z | ||
.object({ | ||
street: z.string().optional(), | ||
city: z.string().optional(), | ||
country: z.string().optional(), | ||
zipCode: z.string().optional(), | ||
}) | ||
.optional(), | ||
phoneNumber: z.string().optional(), | ||
socialLinks: z | ||
.object({ | ||
twitter: z.string().url().optional(), | ||
linkedin: z.string().url().optional(), | ||
github: z.string().url().optional(), | ||
}) | ||
.optional(), | ||
}); | ||
|
||
export const validateProfileSchema = (data: ProfileData) => { | ||
// Check if at least one key from profileSchema is present in the data, excluding userId | ||
const hasAnyKey = Object.keys(profileSchema.shape) | ||
.filter((key) => key !== 'userId') | ||
.some((key) => key in data && data[key as keyof ProfileData] !== undefined); | ||
|
||
if (!hasAnyKey) { | ||
throw new z.ZodError([ | ||
{ | ||
code: z.ZodIssueCode.custom, | ||
path: Object.keys(profileSchema.shape).filter((key) => key !== 'userId'), | ||
message: 'At least one field from the profile schema must be provided', | ||
}, | ||
]); | ||
} | ||
|
||
return profileSchema.parse(data); | ||
}; | ||
|
||
export type ProfileData = z.infer<typeof profileSchema>; | ||
export type CreateProfileData = Omit<ProfileData, 'userId'>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import supertest, { Response } from 'supertest'; | ||
import { CreateProfileData, ProfileData, success } from '@/api/v1/profile'; | ||
import { app } from '@/app'; | ||
import { STATUS_CODES } from '@/constants'; | ||
|
||
export const upSertProfileData = async (payload: CreateProfileData, authorizationHeader: string) => { | ||
return await supertest(app).put('/api/v1/profile').set('authorization', authorizationHeader).send(payload); | ||
}; | ||
|
||
export const expectProfileData = (response: Response, payload: ProfileData) => { | ||
expect(response).toBeDefined(); | ||
expect(response.statusCode).toBe(STATUS_CODES.OK); | ||
|
||
const expectedBody: Partial<ProfileData> & { message: string; status: string } = { | ||
message: success.PROFILE_UPDATED_SUCCESSFULLY, | ||
status: 'success', | ||
userId: payload.userId, | ||
}; | ||
|
||
if (payload.avatar != null) expectedBody.avatar = payload.avatar; | ||
if (payload.bio != null) expectedBody.bio = payload.bio; | ||
if (payload.phoneNumber != null) expectedBody.phoneNumber = payload.phoneNumber; | ||
if (payload.address) expectedBody.address = payload.address; | ||
if (payload.socialLinks) expectedBody.socialLinks = payload.socialLinks; | ||
|
||
expect(response.body).toMatchObject(expectedBody); | ||
}; |