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

nuxt migration -file upload - WIP #271

Merged
merged 2 commits into from
Jan 13, 2024

Conversation

formsdev
Copy link
Collaborator

@formsdev formsdev commented Jan 4, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a unified storeFile function for handling file uploads with support for local and S3 storage.
  • Enhancements

    • Improved file input components by integrating the new storeFile upload functionality.
    • Added an asset utility function for generating asset URLs with environment-specific base paths.
  • Refactor

    • Centralized file upload logic to a single module for better maintainability and reusability.

@formsdev formsdev requested a review from JhumanJ January 4, 2024 11:36
Copy link
Contributor

coderabbitai bot commented Jan 4, 2024

Walkthrough

The recent updates involve refactoring the file upload functionality across different Vue components by centralizing the storeFile function in a separate JavaScript module (file-uploads.js). This function is now imported and used in place of the previous local definitions. Additionally, the opnFetch method has been updated to send a more structured body payload. A utility function asset has been added to handle asset URLs, utilizing an environment variable for path concatenation.

Changes

File Path Change Summary
.../forms/FileInput.vue Imported storeFile from file-uploads.js and modified uploadFileToServer method to use the imported storeFile. Updated opnFetch call within the method to include a structured body object.
.../forms/ImageInput.vue Imported storeFile from file-uploads.js and replaced the usage of local storeFile with the imported one. Modified the body of the opnFetch call to include the URL in the request body.
.../lib/file-uploads.js Introduced storeFile function to handle file uploads with support for local and S3 storage, including progress and cancellation handling.
.../lib/utils.js Added asset function for URL concatenation using an environment variable.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ff9823b and 7de932c.
Files selected for processing (4)
  • client/components/forms/FileInput.vue (3 hunks)
  • client/components/forms/ImageInput.vue (2 hunks)
  • client/lib/file-uploads.js (1 hunks)
  • client/lib/utils.js (1 hunks)
Additional comments: 7
client/lib/file-uploads.js (3)
  • 4-15: For local uploads, the function uses useOpnApi with a hard-coded endpoint /upload-file. Ensure that this endpoint is correct and that the server-side API is expecting the Content-Type to be set to multipart/form-data without a boundary. Some server-side implementations might require the boundary to be specified.

  • 18-56: For S3 uploads, the function dynamically constructs the request options and headers. It's important to ensure that the Host header is not included in the S3 pre-signed URL request, as it is removed on lines 33-35. This is a good security practice to prevent Host header attacks.

  • 43-52: The use of axios.create() to remove default headers is a good practice to avoid sending unnecessary or sensitive information. However, ensure that the cancelToken is properly implemented and tested, as it is crucial for the cancellation feature to work correctly.

client/components/forms/FileInput.vue (2)
  • 82-82: The import statement for storeFile is correct and follows best practices for modularity by using a centralized file upload function.

  • 195-204: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [189-200]

The uploadFileToServer method has been refactored to use the storeFile function. Ensure that the opnFetch call on line 196 is correctly updated to handle the new file upload process, and that the server-side endpoint is expecting the body structure provided.

client/components/forms/ImageInput.vue (2)
  • 113-113: The import statement for storeFile is correct and follows best practices for modularity by using a centralized file upload function.

  • 191-197: The uploadFileToServer method has been refactored to use the storeFile function. Ensure that the opnFetch call on line 193 is correctly updated to handle the new file upload process, and that the server-side endpoint is expecting the body structure provided.

Comment on lines 17 to 20
export const asset = (path) => {
const assetUrl = import.meta.env.VITE_VAPOR_ASSET_URL ? import.meta.env.VITE_VAPOR_ASSET_URL : ''
return assetUrl + '/' + path
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The asset function correctly constructs a URL using the VITE_VAPOR_ASSET_URL environment variable. However, it does not handle the case where the path parameter might already start with a /, which would result in a double slash in the URL. Consider trimming any leading slash from the path parameter before concatenation.

-  return assetUrl + '/' + path
+  return assetUrl + '/' + path.replace(/^\//, '');

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export const asset = (path) => {
const assetUrl = import.meta.env.VITE_VAPOR_ASSET_URL ? import.meta.env.VITE_VAPOR_ASSET_URL : ''
return assetUrl + '/' + path
}
export const asset = (path) => {
const assetUrl = import.meta.env.VITE_VAPOR_ASSET_URL ? import.meta.env.VITE_VAPOR_ASSET_URL : ''
return assetUrl + '/' + path.replace(/^\//, '');
}

Comment on lines +3 to +57
export const storeFile = async (file, options = {}) => {
if(!opnformConfig.s3_enabled) { // If not s3 then upload to local temp
let formData = new FormData()
formData.append('file', file)
const response = await useOpnApi('/upload-file', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
response.data.extension = file.name.split('.').pop()
return response.data
}

const response = await useOpnApi(options.signedStorageUrl ? options.signedStorageUrl : '/vapor/signed-storage-url', {
method: 'POST',
body: options.data,
bucket: options.bucket || '',
content_type: options.contentType || file.type,
expires: options.expires || '',
visibility: options.visibility || '',
baseURL: options.baseURL || null,
headers: options.headers || {},
...options.options
})
console.log("response.data",response.data)

const headers = response.data.headers

if ('Host' in headers) {
delete headers.Host
}

if (typeof options.progress === 'undefined') {
options.progress = () => {}
}

const cancelToken = options.cancelToken || ''

// Remove authorization headers
const cleanAxios = axios.create()
cleanAxios.defaults.headers.common = {}
await cleanAxios.put(response.data.url, file, {
cancelToken: cancelToken,
headers: headers,
onUploadProgress: (progressEvent) => {
options.progress(progressEvent.loaded / progressEvent.total)
}
})

response.data.extension = file.name.split('.').pop()

return response.data
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The storeFile function appears to handle both local and S3 uploads. However, there is a console log statement on line 29 that should be removed to prevent potential leakage of sensitive information in production logs.

-  console.log("response.data",response.data)

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export const storeFile = async (file, options = {}) => {
if(!opnformConfig.s3_enabled) { // If not s3 then upload to local temp
let formData = new FormData()
formData.append('file', file)
const response = await useOpnApi('/upload-file', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
response.data.extension = file.name.split('.').pop()
return response.data
}
const response = await useOpnApi(options.signedStorageUrl ? options.signedStorageUrl : '/vapor/signed-storage-url', {
method: 'POST',
body: options.data,
bucket: options.bucket || '',
content_type: options.contentType || file.type,
expires: options.expires || '',
visibility: options.visibility || '',
baseURL: options.baseURL || null,
headers: options.headers || {},
...options.options
})
console.log("response.data",response.data)
const headers = response.data.headers
if ('Host' in headers) {
delete headers.Host
}
if (typeof options.progress === 'undefined') {
options.progress = () => {}
}
const cancelToken = options.cancelToken || ''
// Remove authorization headers
const cleanAxios = axios.create()
cleanAxios.defaults.headers.common = {}
await cleanAxios.put(response.data.url, file, {
cancelToken: cancelToken,
headers: headers,
onUploadProgress: (progressEvent) => {
options.progress(progressEvent.loaded / progressEvent.total)
}
})
response.data.extension = file.name.split('.').pop()
return response.data
}
export const storeFile = async (file, options = {}) => {
if(!opnformConfig.s3_enabled) { // If not s3 then upload to local temp
let formData = new FormData()
formData.append('file', file)
const response = await useOpnApi('/upload-file', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
})
response.data.extension = file.name.split('.').pop()
return response.data
}
const response = await useOpnApi(options.signedStorageUrl ? options.signedStorageUrl : '/vapor/signed-storage-url', {
method: 'POST',
body: options.data,
bucket: options.bucket || '',
content_type: options.contentType || file.type,
expires: options.expires || '',
visibility: options.visibility || '',
baseURL: options.baseURL || null,
headers: options.headers || {},
...options.options
})
const headers = response.data.headers
if ('Host' in headers) {
delete headers.Host
}
if (typeof options.progress === 'undefined') {
options.progress = () => {}
}
const cancelToken = options.cancelToken || ''
// Remove authorization headers
const cleanAxios = axios.create()
cleanAxios.defaults.headers.common = {}
await cleanAxios.put(response.data.url, file, {
cancelToken: cancelToken,
headers: headers,
onUploadProgress: (progressEvent) => {
options.progress(progressEvent.loaded / progressEvent.total)
}
})
response.data.extension = file.name.split('.').pop()
return response.data
}

@JhumanJ JhumanJ merged commit ff7e1ac into migrate-to-nuxt Jan 13, 2024
0 of 2 checks passed
@JhumanJ JhumanJ deleted the migrate-to-nuxt-file-upload branch January 13, 2024 13:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 7de932c and 3c284c8.
Files selected for processing (2)
  • client/components/forms/FileInput.vue (3 hunks)
  • client/components/forms/ImageInput.vue (2 hunks)
Additional comments: 4
client/components/forms/FileInput.vue (2)
  • 82-82: The import of storeFile from ~/lib/file-uploads.js is correctly placed at the top of the script section, which is a common convention in Vue components.

  • 196-205: > Note: This review was outside the patches, so it was mapped to the patch with the greatest overlap. Original lines [190-202]

The uploadFileToServer method has been refactored to use the storeFile function. Ensure that the storeFile function is thoroughly tested, especially since it's now a centralized method used across different components. Also, verify that the opnFetch method is correctly updated to handle the new body structure and that the backend endpoint is expecting this new payload format.

client/components/forms/ImageInput.vue (2)
  • 113-113: The import of storeFile from ~/lib/file-uploads.js is correctly placed and follows the standard convention in Vue components.

  • 191-197: The uploadFileToServer method has been updated to use the storeFile function. Similar to FileInput.vue, ensure that storeFile is well-tested and that the backend is prepared to handle the new request body format in the opnFetch call.

Comment on lines +199 to +202
body: {
type: 'files',
url: file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The construction of the url property in the body object seems to be manually concatenating parts of the file name and the response from storeFile. Consider creating a utility function to handle this logic, which would improve maintainability and reduce the risk of errors in URL construction.

- url: file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
+ url: constructFileUrl(file.name, response.uuid, response.extension)

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
body: {
type: 'files',
url: file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
}
body: {
type: 'files',
url: constructFileUrl(file.name, response.uuid, response.extension)
}

Comment on lines +195 to +197
body: {
url: this.file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The manual construction of the url property in the body object is repeated here as in FileInput.vue. It would be beneficial to abstract this logic into a utility function for better code reuse and maintainability.

- url: this.file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
+ url: constructFileUrl(this.file.name, response.uuid, response.extension)

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
body: {
url: this.file.name.split('.').slice(0, -1).join('.') + '_' + response.uuid + '.' + response.extension
}
body: {
url: constructFileUrl(this.file.name, response.uuid, response.extension)
}

JhumanJ added a commit that referenced this pull request Jan 15, 2024
* wip

* Managed to load a page

* Stuck at changing routes

* Fixed the router, and editable div

* WIP

* Fix app loader

* WIP

* Fix check-auth middleware

* Started to refactor input components

* WIP

* Added select input, v-click-outside for vselect

* update vselect & phone input

* Fixed the mixin

* input component updates

* Fix signature input import

* input component updates in vue3

* image input in vue3

* small fixes

* fix useFormInput watcher

* scale input in vue3

* Vue3: migrating from vuex to Pinia (#249)

* Vue3: migrating from vuex to Pinia

* toggle input fixes

* update configureCompat

---------

Co-authored-by: Forms Dev <[email protected]>

* support vue3 query builder

* Refactor inpus

* fix: Vue3 Query Builder - Logic Editor (#251)

* support vue3 query builder

* upgrade

* remove local from middleware

* Submission table pagination & migrate chart to vue3 (#254)

* Submission table Pagination in background

* migrate chart to vue3

* Form submissions pagination

* Form submissions

* Fix form starts

* Fix openSelect key issue

---------

Co-authored-by: Forms Dev <[email protected]>
Co-authored-by: Julien Nahum <[email protected]>

* Vue 3 better animation (#257)

* vue-3-better-animation

* Working on migration to vueuse/motion

* Form sidebar animations

* Clean code

* Added animations for modal

* Finished implementing better animations

---------

Co-authored-by: Forms Dev <[email protected]>

* Work in progress

* Migrating amplitude and crisp plugin/composable

* Started to refactor pages

* WIP

* vue3-scroll-shadow-fixes (#260)

* WIP

* WIP

* WIP

* Figured out auth & middlewares

* WI

* Refactoring stores and templates pages to comp. api

* Finishing the templates pages

* fix collapsible

* Finish reworking most templates pages

* Reworked workspaces store

* Working on home page and modal

* Fix dropdown

* Fix modal

* Fixed form creation

* Fixed most of the form/show pages

* Updated cors dependency

* fix custom domain warning

* NuxtLink migration (#262)

Co-authored-by: Forms Dev <[email protected]>

* Tiny fixes + start pre-rendering

* migrate-to-nuxt-useappconfig (#263)

* migrate-to-nuxt-useappconfig

* defineAppConfig

---------

Co-authored-by: Forms Dev <[email protected]>

* Working on form/show and editor

* Globally import form inputs to fix resolve

* Remove vform - working on form public page

* Remove initform mixin

* Work in progress for form create guess user

* Nuxt Migration notifications (#265)

* Nuxt Migration notifications

* @input to @update:model-value

* change field type fixes

* @update:model-value

* Enable form-block-logic-editor

* vue-confetti migration

* PR request changes

* useAlert in setup

* Migrate to nuxt settings page AND remove axios (#266)

* Settings pages migration

* remove axios and use opnFetch

* Make created form reactive (#267)

* Remove verify pages and axios lib

---------

Co-authored-by: Julien Nahum <[email protected]>

* Fix alert styling + bug fixes and cleaning

* Refactor notifications + add shadow

* Fix vselect issue

* Working on page pre-rendering

* Created NotionPages store

* Added sitemap on nuxt side

* Sitemap done, working on aws amplify

* Adding missing module

* Remove axios and commit backend changes to sitemap

* Fix notifications

* fix guestpage editor (#269)

Co-authored-by: Julien Nahum <[email protected]>

* Remove appconfig in favor of runtimeconfig

* Fixed amplitude bugs, and added staging environment

* Added amplify file

* Change basdirectory amplify

* Fix loading bar position

* Fix custom redirect (#273)

* Dirty form handling - nuxt migration (#272)

* SEO meta nuxt migration (#274)

* SEO meta nuxt migration

* Polish seo metas, add defaults for OG and twitter

---------

Co-authored-by: Julien Nahum <[email protected]>

* migrate to nuxt useClipboard (#268)

* Set middleware on pages (#278)

* Se middleware on pages

* Se middleware on account page

* add robots.txt (#276)

* 404 page migration (#277)

* Templates pages migration (#275)

* NuxtImg Migration (#279)

Co-authored-by: Julien Nahum <[email protected]>

* Update package json

* Fix build script

* Add loglevel param

* Disable page pre-rendering

* Attempt to allow svgs

* Fix SVGs with NuxtImage

* Add .env file at AWS build time

* tRGIGGER deploy

* Fix issue

* ANother attrempt

* Fix typo

* Fix env?

* Attempt to simplify build

* Enable swr caching instead of prerenderign

* Better image compression

* Last attempt at nuxt images efficiency

* Improve image optimization again

* Remove NuxtImg for non asset files

* Restore templates pages cache

* Remove useless images + fix templates show page

* image optimization caching + fix hydratation issue form template page

* URL generation (front&back) + fixed authJWT for SSR

* Fix composable issue

* Fix form share page

* Embeddable form as a nuxt middleware

* Fix URL for embeddable middleware

* Debugging embeddable on amplify

* Add custom domain support

* No follow for non-production env

* Fix sentry nuxt and custom domain redirect

* remove api prefix from routes (#280)

* remove api prefix from routes

* PR changes

---------

Co-authored-by: Julien Nahum <[email protected]>

* nuxt migration -file upload - WIP (#271)

Co-authored-by: Julien Nahum <[email protected]>

* Fix local file upload

* Fix file submissions preview

* API redirect to back-end from nuxt

* API redirect to back-end from nuxt

* Remove old JS app, update deploy script

* Fix tests, added gh action nuxt step

* Updated package-lock.json

* Setup node in GH Nuxt action

* Setup client directory for GH workflow

---------

Co-authored-by: Forms Dev <[email protected]>
Co-authored-by: Chirag Chhatrala <[email protected]>
Co-authored-by: Rishi Raj Jain <[email protected]>
Co-authored-by: formsdev <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants