Skip to content

Commit

Permalink
feat(nuxt): add json2csv vue composables
Browse files Browse the repository at this point in the history
  • Loading branch information
productdevbook committed Dec 13, 2023
1 parent e786d18 commit b089778
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { send, setResponseHeader } from 'h3'
import type { SetResponseCsv } from '../types'
import type { SetResponseCsv } from '../../types'

export async function setResponseCsv(data: SetResponseCsv) {
const date = new Date()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AsyncParser } from '@json2csv/node'

import type { PartinalKey } from '../../../core/types'
import type { CsvNodeOpts, NodeJsonParameters, SetResponseCsv } from '../types'
import type { PartinalKey } from '../../../../core/types'
import type { CsvNodeOpts, NodeJsonParameters, SetResponseCsv } from '../../types'
import { setResponseCsv } from './setResponseCsv'

async function nodeCSV(value: NodeJsonParameters) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* @example
* ```ts
* await useFetch('/api/csvDownload', {
method: 'get',
onResponse({ response }) {
download(response._data, 'form.csv')
},
})
* ```
* @param data
* @param filename
*/
function download(data: any, filename: string) {
const defaultMimeType = 'application/octet-stream'
const blob = new Blob([data], { type: defaultMimeType })
const blobURL = window.URL.createObjectURL(blob)

const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = blobURL
tempLink.setAttribute('download', filename)

if (typeof tempLink.download === 'undefined')
tempLink.setAttribute('target', '_blank')

document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(blobURL)
}

export function usePergelJsonCsv() {
return {
download,
}
}
5 changes: 3 additions & 2 deletions packages/nuxt/src/runtime/modules/json2csv/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addServerImportsDir, createResolver } from '@nuxt/kit'
import { addImportsDir, addServerImportsDir, createResolver } from '@nuxt/kit'
import { definePergelModule } from '../../core/definePergel'

export default definePergelModule({
Expand All @@ -14,7 +14,8 @@ export default definePergelModule({
const resolver = createResolver(import.meta.url)
const projectName = options.resolvedModule.projectName

addServerImportsDir(resolver.resolve('./composables'))
addServerImportsDir(resolver.resolve('./composables/server'))
addImportsDir(resolver.resolve('./composables/vue'))

options._contents.push({
moduleName: 'json2csv',
Expand Down

0 comments on commit b089778

Please sign in to comment.