Skip to content

Instantly share code, notes, and snippets.

@davimacedo
Last active June 23, 2021 21:33
Show Gist options
  • Star 39 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save davimacedo/c7738203a2a616b48a22fdc7c00b37d2 to your computer and use it in GitHub Desktop.
Save davimacedo/c7738203a2a616b48a22fdc7c00b37d2 to your computer and use it in GitHub Desktop.
Example of importing data with cloud functions. See a live example at https://www.back4app.com/database/davimacedo/parse-import-example
curl -X POST \
-H "X-Parse-Application-Id: LL9oIdzIkmwl5xyowQQu0fTmXyUWfet9RuAzwHfj" \
-H "X-Parse-REST-API-Key: R3S8PYQKuzeV4c8MUeO5ved46C50MEp56boDHW1O" \
-H "Content-Type: application/json" \
-d @data.json \
https://parseapi.back4app.com/functions/import
{
"className": "ExampleClass",
"rows": [
{ "ExampleColumnA": "row1columnA", "ExampleColumnB": "row1columnB" },
{ "ExampleColumnA": "row2columnA", "ExampleColumnB": "row2columnB"}
]
}
Parse.Cloud.define('import', async request => {
const className = request.params.className;
const rows = request.params.rows;
const MyClass = Parse.Object.extend(className);
var myClassObjects = [];
for (let i = 0; i < rows.length; i++) {
const myClassObject = new MyClass();
for (const column in rows[i]) {
myClassObject.set(column, rows[i][column]);
}
myClassObjects.push(myClassObject);
}
try {
await Parse.Object.saveAll(myClassObjects);
} catch (e) {
throw new Error(`Import failed: ${e}`);
}
return `Successfully imported ${myClassObjects.length} rows into ${className} class`;
});
@miladabc
Copy link

Is there a better way of importing data to parse server?
Imagine thousand of rows to import, I'm worried about those for loops there.

@davimacedo
Copy link
Author

davimacedo commented Jan 5, 2020

@Milad-abbasi I've just updated the example to be compliant with the latest version of Parse and also to use Parse.Object.saveAll(). It conveniently splits the requests in batches so you can make sure it works properly. I also added the link for a living example at the Back4App Database Hub so you can just run and see the imported rows or clone, check the cloud code out and play around.

@randyheaton
Copy link

Little heads up for anyone looking. I feel like there could be a small versioning issue between the function here and the one posted in the live example. The version on this page revised on Jan 5 2020 and current as of June 23 2021 works great for me and also employs the improvements the owner describes in his Jan 5 2020 comment. Whereas the example posted in the live example fails for me at the line Parse.Promise.when(promises).

@davimacedo
Copy link
Author

Thanks for the heads up. I've just updated the live example code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment