Skip to content

Commit

Permalink
refactor(backend,taxonomy-editor-frontend): Handle background task on…
Browse files Browse the repository at this point in the history
… frontend
  • Loading branch information
alice.juan committed Dec 20, 2023
1 parent 95bd60b commit 1f9c964
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 10 deletions.
2 changes: 2 additions & 0 deletions backend/editor/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ class StatusFilter(str, Enum):

OPEN = "OPEN"
CLOSED = "CLOSED"
LOADING = "LOADING"
FAILED = "FAILED"


@app.exception_handler(RequestValidationError)
Expand Down
12 changes: 7 additions & 5 deletions backend/editor/entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,6 @@ async def parse_taxonomy(self, filename):
"""
Helper function to call the Open Food Facts Python Taxonomy Parser
"""
# Close current transaction to use the session variable in parser
await get_current_transaction().commit()

with SyncTransactionCtx() as session:
# Create parser object and pass current session to it
parser_object = parser.Parser(session)
Expand All @@ -110,6 +107,9 @@ async def import_from_github(self, description):
filename = self.taxonomy_name + ".txt"
base_url += filename
try:
async with TransactionCtx():
await self.create_project(description) # Creates a "project node" in neo4j

with tempfile.TemporaryDirectory(prefix="taxonomy-") as tmpdir:
# File to save the downloaded taxonomy
filepath = f"{tmpdir}/{filename}"
Expand All @@ -120,10 +120,12 @@ async def import_from_github(self, description):
status = await self.parse_taxonomy(filepath) # Parse the taxonomy

async with TransactionCtx():
await self.create_project(description) # Creates a "project node" in neo4j
await self.set_project_status(status="OPEN")

return status
except Exception as e:
async with TransactionCtx():
await self.set_project_status(status="FAILED")
raise TaxonomyImportError() from e

async def upload_taxonomy(self, filepath, description):
Expand Down Expand Up @@ -244,7 +246,7 @@ async def create_project(self, description):
"taxonomy_name": self.taxonomy_name,
"branch_name": self.branch_name,
"description": description,
"status": "OPEN",
"status": "LOADING",
}
await get_current_transaction().run(query, params)

Expand Down
6 changes: 4 additions & 2 deletions taxonomy-editor-frontend/src/pages/go-to-project/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,23 @@ const GoToProject = ({ clearNavBarLinks }: Props) => {
const navigate = useNavigate();

const { data, isPending, isError } = useFetch<ProjectsAPIResponse>(
`${API_URL}projects?status=OPEN`
`${API_URL}projects`
);

useEffect(() => {
let newProjects: ProjectType[] = [];

if (data) {
const backendProjects = data.map(
({ id, branch_name, taxonomy_name, description, errors_count }) => {
({ id, branch_name, taxonomy_name, description, errors_count, status }) => {
return {
id, // needed by MaterialTable as key
projectName: id,
taxonomyName: toTitleCase(taxonomy_name),
branchName: branch_name,
description: description,
errors_count: errors_count,
status: status
};
}
);
Expand Down Expand Up @@ -117,6 +118,7 @@ const GoToProject = ({ clearNavBarLinks }: Props) => {
}
},
},
{ title: "Status", field: "status" },
]}
options={{
actionsColumnIndex: -1,
Expand Down
6 changes: 5 additions & 1 deletion taxonomy-editor-frontend/src/pages/root-nodes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const RootNodes = ({
);
}

if (isPending || !nodes) {
if (isPending || !nodes || nodes.length === 0) {
return (
<Box
sx={{
Expand All @@ -93,6 +93,10 @@ const RootNodes = ({
}}
>
<CircularProgress />
<Typography sx={{ m: 5 }} variant="h6">
Taxonomy parsing may take several minutes, depending on the complexity of the taxonomy being imported.<br/>
Kindly refresh the page to view the updated status of the project.
</Typography>
</Box>
);
}
Expand Down
6 changes: 4 additions & 2 deletions taxonomy-editor-frontend/src/pages/startproject/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const StartProject = ({ clearNavBarLinks }) => {
const baseUrl = createBaseURL(toSnakeCase(taxonomyName), branchName);
setLoading(true);
const dataToBeSent = { description: description };
let errorMessage : string = "Unable to import";

fetch(`${baseUrl}import`, {
method: "POST",
Expand All @@ -51,12 +52,13 @@ const StartProject = ({ clearNavBarLinks }) => {
.then(async (response) => {
const responseBody = await response.json();
if (!response.ok) {
throw new Error(responseBody?.detail ?? "Unable to import");
errorMessage = responseBody?.detail ?? "Unable to import";
throw new Error(errorMessage);
}
navigate(`/${toSnakeCase(taxonomyName)}/${branchName}/entry`);
})
.catch(() => {
setErrorMessage("Unable to import");
setErrorMessage(errorMessage);
})
.finally(() => setLoading(false));
};
Expand Down

0 comments on commit 1f9c964

Please sign in to comment.