Skip to content
This repository has been archived by the owner on Aug 29, 2023. It is now read-only.

Commit

Permalink
fix: organised settings, api response schema
Browse files Browse the repository at this point in the history
  • Loading branch information
soulsam480 committed Sep 23, 2021
1 parent fe5db6f commit b34e8b4
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 30 deletions.
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}
"typescript.tsdk": "node_modules/typescript/lib"
}
5 changes: 2 additions & 3 deletions api/src/controllers/cdn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GetObjectCommandInput, PutObjectCommandInput } from '@aws-sdk/client-s3
import { v4 as uuid } from 'uuid';
import { upload } from 'src/middlewares/multer';
import { getObject, getObjects, putObject } from 'src/services/cdn';
import { normalize, parseEnv } from 'src/utils/helpers';
import { formatResponse, normalize, parseEnv } from 'src/utils/helpers';
import { Router } from 'express';
import { auth } from 'src/middlewares/auth';

Expand Down Expand Up @@ -40,15 +40,14 @@ cdnRouter.post('/', upload, async (req, res) => {

await putObject(objectParams);

return res.json({ key: file_name });
return res.json(formatResponse({ key: file_name }));
} catch (error) {
console.log(error);

return res.status(500).send('Internal server error !');
}
});


//TODO: send file_name in query
// e.g. http://localhost:3000/cdn/file?file_name=4df12050-a54f-46b7-99e0-42730d9d4127--June_logo.svg
cdnRouter.get('/file', async (req, res) => {
Expand Down
3 changes: 1 addition & 2 deletions api/src/services/cdn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
PutObjectCommandInput,
} from '@aws-sdk/client-s3';
import { s3 } from 'src/db/s3';
import { userModel } from 'src/entities/user';
import { parseEnv, streamToString } from 'src/utils/helpers';

const BUCKET = parseEnv<string>('BUCKET_NAME');
Expand Down Expand Up @@ -48,4 +47,4 @@ export async function getObject(data: GetObjectCommandInput) {
} catch (error) {
Promise.reject(error);
}
}
}
71 changes: 51 additions & 20 deletions app/src/User/pages/settings/ProfileSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import JContainer from 'src/Lib/JContainer';
import JInput from 'src/Lib/JInput';
import { useUserStore } from 'src/User/store/useUserStore';
import { useAlert } from 'src/Lib/store/alerts';
import { updateUserById, uploadImage } from '../../services/users';
import { UpdateUserData, User } from 'src/utils/types';
import { updateUserById, uploadImage } from 'src/User/services/users';
import { UpdateUserData } from 'src/utils/types';
import { useNavigate } from 'react-router-dom';
import { useLoader } from 'src/Shared/store/loader';
import { diffMatcher } from 'src/utils/helpers';
Expand All @@ -21,7 +21,7 @@ const ProfileSettings: React.FC<Props> = () => {
const navigate = useNavigate();

const inputFile = useRef<HTMLInputElement>(null);
const uploadFile = useRef<File | null>(null); //React.RefObject<HTMLInputElement>
const uploadFile = useRef<File | null>(null);

const [userDetails, setUserDetails] = useState<UpdateUserData>({
name: user.name,
Expand All @@ -30,23 +30,55 @@ const ProfileSettings: React.FC<Props> = () => {
image: user.image,
username: user.username,
});

function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
if (e.target.files) {
uploadFile.current = e.target.files[0];
}
}

async function uploadProfileImage() {
if (!uploadFile.current) return;

try {
const formData = new FormData();
formData.append('file', uploadFile.current);

const {
data: {
data: { key: image },
},
} = await uploadImage(formData);

uploadFile.current = null;

return image;
} catch (error) {
throw 'Unable to upload profile picture.';
}
}

const updateUserDetails = async (e: FormEvent) => {
e.preventDefault();

let diffData = diffMatcher(user, userDetails);

try {
setLoader(true);
if (uploadFile.current) {
const formData = new FormData();
formData.append('file', uploadFile.current);
const imageKey = await uploadImage(formData);
diffData = { ...diffData, image: imageKey.data.key };
}

const image = await uploadProfileImage();

diffData = { ...diffData, image };

if (!Object.keys(diffData).length) return;

const {
data: { data: userFromResponse },
} = await updateUserById(user.id, diffData);

setUser({ ...userFromResponse });
setAlert({ type: 'success', message: 'Updated successfully' });

navigate('/');
} catch (error) {
setAlert({ type: 'danger', message: 'Unable to update user' });
Expand Down Expand Up @@ -84,27 +116,25 @@ const ProfileSettings: React.FC<Props> = () => {
type="file"
id="file"
ref={inputFile}
style={{ display: 'none' }}
onChange={(e) => {
if (e.target.files) {
uploadFile.current = e.target.files[0];
}
}}
className="hidden invisible"
multiple={false}
onChange={handleFileChange}
/>

<JContainer className="flex flex-col space-y-4 rounded-lg py-5">
<JInput
label="name"
id="name"
value={userDetails.name}
onInput={(name) => setUserDetails({ ...userDetails, name })}
onInput={(name) => setUserDetails((u) => ({ ...u, name }))}
type="text"
/>

<JInput
label="username"
id="username"
value={userDetails.username}
onInput={(username) => setUserDetails({ ...userDetails, username })}
onInput={(username) => setUserDetails((u) => ({ ...u, username }))}
type="text"
/>

Expand All @@ -113,15 +143,15 @@ const ProfileSettings: React.FC<Props> = () => {
label="Email"
id="email"
value={userDetails.email}
onInput={(email) => setUserDetails({ ...userDetails, email })}
type="text"
onInput={(email) => setUserDetails((u) => ({ ...u, email }))}
type="email"
/>

<JInput
label="bio"
id="bio"
value={userDetails.bio}
onInput={(bio) => setUserDetails({ ...userDetails, bio })}
onInput={(bio) => setUserDetails((u) => ({ ...u, bio }))}
is="textarea"
/>

Expand All @@ -133,4 +163,5 @@ const ProfileSettings: React.FC<Props> = () => {
</div>
);
};

export default ProfileSettings;
5 changes: 3 additions & 2 deletions app/src/User/services/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ export function getUserPostsById(id: string, opts: PaginationParams) {
export function updateUserById(id: string, userData: UpdateUserData) {
return api.patch<ResponseSchema<User>>(`/users/${id}`, { ...userData });
}

export function updateUserPassword(id: string, passwords: UpdatePassword) {
return api.post<ResponseSchema<User>>(`/users/${id}/password`, { ...passwords });
}

export function uploadImage(file: any) {
return api.post<ResponseSchema<User>>(`/cdn`, file);
export function uploadImage(file: FormData) {
return api.post<ResponseSchema<{ key?: string }>>(`/cdn`, file);
}
1 change: 0 additions & 1 deletion app/src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ export interface Result {
export type hookType = 'start' | 'cancel' | 'typing';

export interface ResponseSchema<T = any> {
key: string | undefined;
data: T;
total_count?: number;
has_more?: boolean;
Expand Down

0 comments on commit b34e8b4

Please sign in to comment.