Skip to content

Commit

Permalink
feat(upload): refacto files in typescript (#1050)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxgfr authored Oct 9, 2023
1 parent bcb1856 commit a70fc4f
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 33 deletions.
3 changes: 3 additions & 0 deletions targets/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@types/formidable": "^2.0.5",
"@types/jest": "^27.4.0",
"@types/jsonwebtoken": "^9.0.3",
"@types/lodash.get": "^4.4.7",
"@types/react": "^17.0.24",
"@types/react-dom": "^18.0.11",
"@urql/devtools": "^2.0.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import { getContainerBlobs, uploadBlob } from "src/lib/azure";
import { isUploadFileSafe } from "src/lib/secu";
import * as stream from "stream";
import { HASURA_GRAPHQL_JWT_SECRET } from "../../../config";
import { NextApiRequest, NextApiResponse } from "next";

const container = process.env.STORAGE_CONTAINER ?? "cdtn-dev";
const jwtSecret = JSON.parse(HASURA_GRAPHQL_JWT_SECRET);

async function endPoint(req, res) {
async function endPoint(req: NextApiRequest, res: NextApiResponse) {
const apiError = createErrorFor(res);
const { token } = req.headers;
const { token }: any = req.headers;

if (!token || !verify(token, jwtSecret.key, { algorithms: jwtSecret.type })) {
return apiError(Boom.badRequest("wrong token"));
Expand All @@ -30,12 +31,12 @@ async function endPoint(req, res) {
}
}

const errored = (res, err) => {
const errored = (res: NextApiResponse, err: any) => {
console.error("[storage]", err);
res.status(400).json({ success: false });
};

const done = (res) => res.status(200).json({ success: true });
const done = (res: NextApiResponse) => res.status(200).json({ success: true });

const ALLOWED_EXTENSIONS = [
"pdf",
Expand All @@ -52,19 +53,19 @@ const ALLOWED_EXTENSIONS = [
"odt",
];

const isAllowedFile = (part) =>
const isAllowedFile = (part: any) =>
ALLOWED_EXTENSIONS.includes(part.name.toLowerCase().split(".").reverse()[0]);

function uploadFiles(req, res) {
function uploadFiles(req: NextApiRequest, res: NextApiResponse) {
const form = new IncomingForm({ multiples: true });
// we need to override the onPart method to directly
// stream the data to azure
let uploadingFilesNumber = 0;
form.onPart = async function (part) {
try {
uploadingFilesNumber++;
const streamCheckup = part.pipe(new stream.PassThrough());
const streamUpload = part.pipe(new stream.PassThrough());
const streamCheckup: any = part.pipe(new stream.PassThrough());
const streamUpload: any = part.pipe(new stream.PassThrough());
streamUpload.name = part.name;
streamUpload.mimetype = part.mimetype;

Expand Down Expand Up @@ -99,7 +100,7 @@ function uploadFiles(req, res) {
});
}

async function getFiles(req, res) {
async function getFiles(_req: NextApiRequest, res: NextApiResponse) {
res.json(await getContainerBlobs(container));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,21 @@ import {
const listFiles = () =>
request(`/api/storage`, {
headers: { token: getToken()?.jwt_token || "" },
});
} as any);

const uploadFiles = (formData) =>
const uploadFiles = (formData: any) =>
request(`/api/storage`, {
body: formData,
headers: { token: getToken()?.jwt_token || "" },
});
} as any);

const deleteFile = (path) =>
const deleteFile = (path: any) =>
request(`/api/storage/${path}`, {
headers: { token: getToken()?.jwt_token || "" },
method: "DELETE",
});
} as any);

const onDeleteClick = function (file) {
const onDeleteClick = function (file: any) {
const confirmed = confirm(
`Êtes-vous sûr(e) de vouloir définitivement supprimer ${file.name} ?`
);
Expand All @@ -64,9 +64,9 @@ const onDeleteClick = function (file) {
function FilesPage() {
const { data, error, isValidating } = useSWR("files", listFiles, {
initialData: undefined,
});
} as any);
const [search, setSearch, setDebouncedSearch] = useDebouncedState("", 400);
const searchInputEl = useRef(null);
const searchInputEl = useRef<any>(null);
const [isSearching, setSearching] = useState(false);
const [filter, setFilter] = useState("");
const [sort, setSort] = useState("mostRecent");
Expand Down Expand Up @@ -101,7 +101,7 @@ function FilesPage() {
});
}}
/>
<Box sx={{ display: "flex" }} as="form" my="medium">
<Box sx={{ display: "flex" }} component="form" my="medium">
<Box
sx={{ display: "flex", alignItems: "flex-end", position: "relative" }}
>
Expand Down Expand Up @@ -180,7 +180,7 @@ function FilesPage() {
<List sx={{ listStyleType: "none", m: 0, p: 0 }}>
{data
.filter(
(file) =>
(file: any) =>
filterCallback(filter, file) &&
(search
? file.name
Expand All @@ -189,7 +189,7 @@ function FilesPage() {
: true)
)
.sort(getSortCallback(sort))
.map((file) => {
.map((file: any) => {
return (
<ListItem
key={file.name}
Expand All @@ -198,6 +198,7 @@ function FilesPage() {
}}
>
<Card
component="a"
target="_blank"
rel="noopener noreferrer"
href={file.url}
Expand Down Expand Up @@ -253,17 +254,17 @@ function FilesPage() {
variant="secondary"
text={file.name}
copied={currentClip === file.name}
onClip={(text) => {
onClip={(text: any) => {
setCurrentClip(text);
}}
/>
<Button
{...buttonProps}
variant="outlined"
onClick={(evt) => {
evt.preventDefault();
onDeleteClick(file);
}}
sx={{ flex: "0 0 auto", mx: theme.space.xsmall }}
>
<IoIosTrash style={iconSx} />
Supprimer
Expand All @@ -285,7 +286,7 @@ export default withCustomUrqlClient(withUserProvider(FilesPage));

const buttonProps = {
outline: true,
size: "small",
size: theme.space.small,
sx: { flex: "0 0 auto", mx: theme.space.xsmall },
type: "button",
};
Expand All @@ -296,7 +297,7 @@ const iconSx = {
width: theme.sizes.iconSmall,
};

const filterCallback = (filter, file) => {
const filterCallback = (filter: any, file: any) => {
const extension = file.name.split(".").pop().toLowerCase();
switch (filter) {
case "jpg":
Expand All @@ -314,23 +315,23 @@ const filterCallback = (filter, file) => {
}
};

const getSortCallback = (sort) => {
const getSortCallback = (sort: any) => {
switch (sort) {
case "alphabetic":
return (a, b) => a.name.localeCompare(b.name);
return (a: any, b: any) => a.name.localeCompare(b.name);
case "reverse-alphabetic":
return (a, b) => b.name.localeCompare(a.name);
return (a: any, b: any) => b.name.localeCompare(a.name);
case "oldest":
return (a, b) =>
return (a: any, b: any) =>
new Date(a.lastModified).getTime() - new Date(b.lastModified).getTime();
case "mostRecent":
return (a, b) =>
return (a: any, b: any) =>
new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime();
case "lightest":
return (a, b) => a.contentLength - b.contentLength;
return (a: any, b: any) => a.contentLength - b.contentLength;
case "heaviest":
return (a, b) => b.contentLength - a.contentLength;
return (a: any, b: any) => b.contentLength - a.contentLength;
default:
return (a, b) => a.name.localeCompare(b.name);
return (a: any, b: any) => a.name.localeCompare(b.name);
}
};
30 changes: 29 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6494,7 +6494,7 @@ __metadata:
languageName: node
linkType: hard

"@types/jest@npm:^27.0.0, @types/jest@npm:^27.0.1, @types/jest@npm:^27.4.1":
"@types/jest@npm:^27.0.0, @types/jest@npm:^27.0.1, @types/jest@npm:^27.4.0, @types/jest@npm:^27.4.1":
version: 27.5.2
resolution: "@types/jest@npm:27.5.2"
dependencies:
Expand Down Expand Up @@ -6529,6 +6529,15 @@ __metadata:
languageName: node
linkType: hard

"@types/jsonwebtoken@npm:^9.0.3":
version: 9.0.3
resolution: "@types/jsonwebtoken@npm:9.0.3"
dependencies:
"@types/node": "*"
checksum: 2debf3adb19b827a023205234ec439b7258aee6ca9273472abe360738a84f08db78c6e853172e842ec303169ec0bb2df39701ab9a13b9e7868fe284ef9136567
languageName: node
linkType: hard

"@types/keyv@npm:^3.1.1, @types/keyv@npm:^3.1.4":
version: 3.1.4
resolution: "@types/keyv@npm:3.1.4"
Expand All @@ -6538,6 +6547,22 @@ __metadata:
languageName: node
linkType: hard

"@types/lodash.get@npm:^4.4.7":
version: 4.4.7
resolution: "@types/lodash.get@npm:4.4.7"
dependencies:
"@types/lodash": "*"
checksum: 0dbf1960606e4707c34e8ffbe97ffaad0e47fc5df7a6e24ea6e4fe5838d2468aa13360f38815c77b06e3c9932631ae15662b4139036a69ee16aeb54827a21405
languageName: node
linkType: hard

"@types/lodash@npm:*":
version: 4.14.199
resolution: "@types/lodash@npm:4.14.199"
checksum: e68d1fcbbfce953ed87b296a628573f62939227bcda0c934954e862b421e8a34c5e71cad6fea27b9980567909e6a4698f09025692958e36d64ea9ed99ec6fb2e
languageName: node
linkType: hard

"@types/mdast@npm:^3.0.0":
version: 3.0.11
resolution: "@types/mdast@npm:3.0.11"
Expand Down Expand Up @@ -12324,6 +12349,9 @@ __metadata:
"@tiptap/react": ^2.1.10
"@tiptap/starter-kit": ^2.0.3
"@types/formidable": ^2.0.5
"@types/jest": ^27.4.0
"@types/jsonwebtoken": ^9.0.3
"@types/lodash.get": ^4.4.7
"@types/react": ^17.0.24
"@types/react-dom": ^18.0.11
"@urql/devtools": ^2.0.3
Expand Down

0 comments on commit a70fc4f

Please sign in to comment.