|
| 1 | +import supabase from "../../supabase.app.mjs"; |
| 2 | +import fs from "fs"; |
| 3 | +import { parse } from "csv-parse/sync"; |
| 4 | + |
| 5 | +export default { |
| 6 | + key: "supabase-batch-insert-rows", |
| 7 | + name: "Batch Insert Rows", |
| 8 | + description: "Inserts new rows into a database. [See the documentation](https://supabase.com/docs/reference/javascript/insert)", |
| 9 | + version: "0.0.1", |
| 10 | + type: "action", |
| 11 | + props: { |
| 12 | + supabase, |
| 13 | + table: { |
| 14 | + propDefinition: [ |
| 15 | + supabase, |
| 16 | + "table", |
| 17 | + ], |
| 18 | + description: "Name of the table to insert rows into", |
| 19 | + }, |
| 20 | + source: { |
| 21 | + type: "string", |
| 22 | + label: "Source of data", |
| 23 | + description: "Whether to enter the row data as an array of objects or to import from a CSV file", |
| 24 | + options: [ |
| 25 | + "Array", |
| 26 | + "CSV File", |
| 27 | + ], |
| 28 | + reloadProps: true, |
| 29 | + }, |
| 30 | + }, |
| 31 | + async additionalProps() { |
| 32 | + const props = {}; |
| 33 | + if (this.source === "Array") { |
| 34 | + props.data = { |
| 35 | + type: "string[]", |
| 36 | + label: "Row Data", |
| 37 | + description: "An array of objects, each object representing a row. Enter column names and values as key/value pairs", |
| 38 | + }; |
| 39 | + } |
| 40 | + if (this.source === "CSV File") { |
| 41 | + props.filePath = { |
| 42 | + type: "string", |
| 43 | + label: "File Path", |
| 44 | + description: "The path to a csv file in the `/tmp` directory. [See the documentation on working with files](https://pipedream.com/docs/code/nodejs/working-with-files/#writing-a-file-to-tmp)", |
| 45 | + }; |
| 46 | + } |
| 47 | + return props; |
| 48 | + }, |
| 49 | + methods: { |
| 50 | + parseArray(arr) { |
| 51 | + if (Array.isArray(arr)) { |
| 52 | + return arr.map((item) => { |
| 53 | + return typeof item === "string" |
| 54 | + ? JSON.parse(item) |
| 55 | + : item; |
| 56 | + }); |
| 57 | + } |
| 58 | + if (typeof arr === "string") { |
| 59 | + return JSON.parse(arr); |
| 60 | + } |
| 61 | + }, |
| 62 | + getRowsFromCSV(filePath) { |
| 63 | + const fileContent = fs.readFileSync(filePath.includes("tmp/") |
| 64 | + ? filePath |
| 65 | + : `/tmp/${filePath}`, "utf-8"); |
| 66 | + const rows = parse(fileContent, { |
| 67 | + columns: true, |
| 68 | + skip_empty_lines: true, |
| 69 | + }); |
| 70 | + return rows; |
| 71 | + }, |
| 72 | + }, |
| 73 | + async run({ $ }) { |
| 74 | + const data = this.source === "CSV File" |
| 75 | + ? this.getRowsFromCSV(this.filePath) |
| 76 | + : this.parseArray(this.data); |
| 77 | + |
| 78 | + const response = await this.supabase.insertRow(this.table, data); |
| 79 | + |
| 80 | + $.export("$summary", `Successfully inserted rows into table ${this.table}`); |
| 81 | + return response; |
| 82 | + }, |
| 83 | +}; |
0 commit comments