### Clone and Install Parse SDK Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Clone the Parse SDK repository, navigate to the directory, install dependencies, and open the project in VS Code. This is the initial setup for local development. ```sh git clone https://github.com/parse-community/Parse-SDK-JS cd Parse-SDK-JS npm install code . ``` -------------------------------- ### Real-time Chat Application Setup Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Example of setting up a real-time chat subscription. It listens for new messages and displays them, including sender information. ```javascript // Example: Real-time chat application async function setupChat(roomId) { const chatQuery = new Parse.Query('ChatMessage'); chatQuery.equalTo('room', roomId); chatQuery.include('sender'); const chatSubscription = await chatQuery.subscribe(); chatSubscription.on('create', (msg) => { const sender = msg.get('sender'); displayMessage({ text: msg.get('text'), sender: sender.get('username'), timestamp: msg.createdAt }); }); return chatSubscription; } ``` -------------------------------- ### Install Parse SDK from GitHub Fork Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md You can install the Parse SDK directly from a GitHub fork or branch by specifying the repository and branch in your npm install command. ```bash npm install github:myUsername/Parse-SDK-JS#my-awesome-feature ``` -------------------------------- ### Login with GET Method Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/changelogs/CHANGELOG_release.md Override the default POST login method by setting the usePost option to false. ```javascript Parse.User.logIn('username', 'password', { usePost: false }) ``` -------------------------------- ### Manage Parse Background Jobs Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Start, monitor, and retrieve information about background jobs. Requires the Master Key for starting jobs. ```javascript // Start a background job (requires Master Key) const jobStatusId = await Parse.Cloud.startJob('sendNewsletters', { templateId: 'weekly-digest', targetAudience: 'active-users' }); console.log('Job started with status ID:', jobStatusId); // Check job status const jobStatus = await Parse.Cloud.getJobStatus(jobStatusId); console.log('Job status:', jobStatus.get('status')); console.log('Job message:', jobStatus.get('message')); // Output: Job status: running // Output: Job message: Processing 1000 of 5000 users // Get available jobs data const jobsData = await Parse.Cloud.getJobsData(); console.log('Available jobs:', jobsData); ``` -------------------------------- ### Create and Use Parse.GeoPoint Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Demonstrates how to create Parse.GeoPoint objects in various ways and access their latitude and longitude properties. Also shows how to get the user's current location in a browser environment. ```javascript // Create a GeoPoint const point = new Parse.GeoPoint(37.7749, -122.4194); // San Francisco console.log('Latitude:', point.latitude); console.log('Longitude:', point.longitude); ``` ```javascript // Alternative ways to create GeoPoints const pointFromArray = new Parse.GeoPoint([37.7749, -122.4194]); const pointFromObject = new Parse.GeoPoint({ latitude: 37.7749, longitude: -122.4194 }); ``` ```javascript // Get user's current location (browser only) try { const currentLocation = await Parse.GeoPoint.current({ enableHighAccuracy: true, timeout: 10000, maximumAge: 60000 }); console.log('Current location:', currentLocation.latitude, currentLocation.longitude); } catch (error) { console.error('Geolocation error:', error.message); } ``` -------------------------------- ### Configure Parse Core Manager Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md The Parse SDK's Core Manager allows customization of configurations and controllers before SDK initialization. Examples include setting request attempt limits or replacing the REST controller. ```javascript // Configuration example Parse.CoreManager.set('REQUEST_ATTEMPT_LIMIT', 1) // Controller example Parse.CoreManager.setRESTController(MyRESTController); ``` -------------------------------- ### Get Current User (Synchronous and Asynchronous) Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Retrieve the currently logged-in user. `Parse.User.current()` is synchronous and browser-only, while `Parse.User.currentAsync()` works in all environments. ```javascript // Get current user (synchronous - browser only) const currentUser = Parse.User.current(); if (currentUser) { console.log('Current user:', currentUser.getUsername()); } // Get current user (async - works everywhere) const currentUserAsync = await Parse.User.currentAsync(); ``` -------------------------------- ### Initialize Parse SDK Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Configure the SDK with application credentials and server URLs. Use the master key only in secure server-side environments. ```javascript // Browser/React Native initialization import Parse from 'parse'; Parse.initialize('YOUR_APP_ID', 'YOUR_JAVASCRIPT_KEY'); Parse.serverURL = 'https://your-parse-server.com/parse'; // Node.js initialization with Master Key const Parse = require('parse/node'); Parse.initialize('YOUR_APP_ID', 'YOUR_JAVASCRIPT_KEY', 'YOUR_MASTER_KEY'); Parse.serverURL = 'https://your-parse-server.com/parse'; // Enable local datastore for offline support Parse.enableLocalDatastore(); // Example with all configuration options Parse.initialize('YOUR_APP_ID'); Parse.serverURL = 'https://your-parse-server.com/parse'; Parse.liveQueryServerURL = 'wss://your-parse-server.com/parse'; Parse.enableEncryptedUser(); Parse.secret = 'my-encryption-key'; ``` -------------------------------- ### Create and Save Parse.File Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Demonstrates creating files from various data sources including base64, byte arrays, browser inputs, Node.js buffers, and streams. ```javascript // Create file from base64 data const base64Data = 'SGVsbG8gV29ybGQh'; // "Hello World!" in base64 const file = new Parse.File('hello.txt', { base64: base64Data }); try { await file.save(); console.log('File URL:', file.url()); // Output: File URL: https://your-server.com/parse/files/appId/abc123_hello.txt } catch (error) { console.error('File upload failed:', error.message); } // Create file from byte array const bytes = [72, 101, 108, 108, 111]; // "Hello" const byteFile = new Parse.File('hello.txt', bytes, 'text/plain'); await byteFile.save(); // Browser: Create file from file input const fileInput = document.getElementById('fileInput'); const selectedFile = fileInput.files[0]; const parseFile = new Parse.File(selectedFile.name, selectedFile); // Upload with progress tracking await parseFile.save({ progress: (progressValue, loaded, total) => { if (progressValue !== null) { console.log(`Upload progress: ${Math.round(progressValue * 100)}%`); console.log(`${loaded} of ${total} bytes`); } } }); // Node.js: Create file from Buffer const fs = require('fs'); const buffer = fs.readFileSync('/path/to/image.png'); const bufferFile = new Parse.File('image.png', buffer, 'image/png'); await bufferFile.save(); // Node.js: Create file from Stream (memory efficient for large files) const stream = fs.createReadStream('/path/to/large-video.mp4'); const streamFile = new Parse.File('video.mp4', stream, 'video/mp4'); await streamFile.save(); ``` -------------------------------- ### Become a User with Session Token Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Re-establish a user session using a previously obtained session token. ```javascript // Become a user with session token const userFromToken = await Parse.User.become('r:pnktnjyb996sj4p156gjtp4im'); ``` -------------------------------- ### Watch and Rebuild SDK for Browser Platform Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Continuously rebuilds the SDK for the browser platform automatically upon each file save. Use this during development for browser-specific changes. ```sh npm run watch:browser ``` -------------------------------- ### Sign Up a New User with Parse.User Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Use this snippet to register a new user account. It includes setting username, password, email, and custom fields, with error handling for common issues like taken usernames or emails. ```javascript // Sign up a new user const user = new Parse.User(); user.set('username', 'johndoe'); user.set('password', 'secretPassword123'); user.set('email', 'john@example.com'); user.set('phone', '+1234567890'); // Custom fields try { await user.signUp(); console.log('User signed up successfully:', user.id); console.log('Session token:', user.getSessionToken()); // Output: User signed up successfully: abc123 // Output: Session token: r:pnktnjyb996sj4p156gjtp4im } catch (error) { switch (error.code) { case Parse.Error.USERNAME_TAKEN: console.error('Username already taken'); break; case Parse.Error.EMAIL_TAKEN: console.error('Email already registered'); break; default: console.error('Signup error:', error.message); } } ``` -------------------------------- ### Watch and Rebuild SDK for Browser Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Continuously rebuilds the SDK for the browser platform automatically upon each file save. Use this during development for browser-specific changes. ```sh npm run watch ``` -------------------------------- ### Manage Local Datastore Operations Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Use these methods to enable the datastore, pin or unpin objects, and perform offline-first queries. Call Parse.enableLocalDatastore() once at application startup. ```javascript // Enable Local Datastore (call once at app start) Parse.enableLocalDatastore(); // Pin objects to local storage const task = new Parse.Object('Task'); task.set('title', 'Buy groceries'); task.set('completed', false); await task.save(); await task.pin(); // Store locally // Pin with a specific label await task.pinWithName('my-tasks'); // Pin multiple objects const tasks = await new Parse.Query('Task').find(); await Parse.Object.pinAll(tasks); await Parse.Object.pinAllWithName('all-tasks', tasks); // Query from local datastore const localQuery = new Parse.Query('Task'); localQuery.fromLocalDatastore(); localQuery.equalTo('completed', false); const localTasks = await localQuery.find(); console.log('Local incomplete tasks:', localTasks.length); // Query from pinned label const myTasksQuery = new Parse.Query('Task'); myTasksQuery.fromPinWithName('my-tasks'); const myTasks = await myTasksQuery.find(); // Unpin objects await task.unPin(); await task.unPinWithName('my-tasks'); await Parse.Object.unPinAll(tasks); await Parse.Object.unPinAllWithName('all-tasks'); // Unpin all objects await Parse.Object.unPinAllObjects(); await Parse.Object.unPinAllObjectsWithName('my-tasks'); // Save eventually (saves when network available) const offlineTask = new Parse.Object('Task'); offlineTask.set('title', 'Offline task'); offlineTask.set('completed', false); await offlineTask.saveEventually(); // Destroy eventually await offlineTask.destroyEventually(); // Fetch from server and update local const serverQuery = new Parse.Query('Task'); const serverTasks = await serverQuery.find(); await Parse.Object.pinAll(serverTasks); // Check if object is pinned // Query local first, fall back to network async function getTasksWithFallback() { const localQuery = new Parse.Query('Task'); localQuery.fromLocalDatastore(); let tasks = await localQuery.find(); if (tasks.length === 0) { // No local data, fetch from server const serverQuery = new Parse.Query('Task'); tasks = await serverQuery.find(); await Parse.Object.pinAll(tasks); } return tasks; } ``` -------------------------------- ### Querying Data with Parse.Query Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Demonstrates various query techniques including basic constraints, pagination, field selection, string matching, array operations, relational subqueries, compound OR queries, aggregation pipelines, and utility methods like count and distinct. ```javascript // Basic query with constraints const query = new Parse.Query('GameScore'); query.equalTo('playerName', 'Sean Plott'); query.greaterThan('score', 1000); query.lessThanOrEqualTo('score', 5000); query.limit(10); query.skip(20); // For pagination query.descending('score'); const results = await query.find(); console.log('Found', results.length, 'scores'); // Output: Found 10 scores results.forEach(score => { console.log(`${score.get('playerName')}: ${score.get('score')}`); }); // Select specific fields to return query.select('score', 'playerName'); const partialResults = await query.find(); // String queries const nameQuery = new Parse.Query('GameScore'); nameQuery.startsWith('playerName', 'Sean'); nameQuery.contains('playerName', 'Plott'); nameQuery.matches('playerName', /^[A-Z]/i); // Regex support // Array queries const tagQuery = new Parse.Query('Post'); tagQuery.containsAll('tags', ['javascript', 'parse']); tagQuery.containedIn('status', ['published', 'featured']); tagQuery.notContainedIn('status', ['draft', 'archived']); // Relational queries const commentQuery = new Parse.Query('Comment'); const postQuery = new Parse.Query('Post'); postQuery.equalTo('author', currentUser); commentQuery.matchesQuery('post', postQuery); // Subquery const comments = await commentQuery.find(); // Compound queries (OR) const loserQuery = new Parse.Query('GameScore'); loserQuery.lessThan('score', 100); const winnerQuery = new Parse.Query('GameScore'); winnerQuery.greaterThan('score', 9000); const combinedQuery = Parse.Query.or(loserQuery, winnerQuery); const extremeScores = await combinedQuery.find(); // Aggregate queries const pipeline = [ { match: { score: { $gt: 100 } } }, { group: { objectId: '$playerName', totalScore: { $sum: '$score' } } }, { sort: { totalScore: -1 } }, { limit: 10 } ]; const aggregateResults = await query.aggregate(pipeline); console.log('Top players:', aggregateResults); // Count and exists const count = await query.count(); console.log('Total matching records:', count); // Output: Total matching records: 42 // Distinct values const distinctNames = await query.distinct('playerName'); console.log('Unique players:', distinctNames); // Get first result const topScore = await new Parse.Query('GameScore') .descending('score') .first(); console.log('Highest score:', topScore?.get('score')); ``` -------------------------------- ### Retrieve and Delete Files Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Retrieves file data with progress tracking and deletes files using the Master Key. ```javascript // Retrieve file data const photoQuery = new Parse.Query('Photo'); const fetchedPhoto = await photoQuery.get(photo.id); const fetchedFile = fetchedPhoto.get('image'); const fileData = await fetchedFile.getData({ progress: (progressValue, loaded, total) => { console.log(`Download progress: ${Math.round(progressValue * 100)}%`); } }); console.log('File content (base64):', fileData.substring(0, 50) + '...'); // Delete a file (requires Master Key) await imageFile.destroy({ useMasterKey: true }); ``` -------------------------------- ### Watch and Rebuild SDK for Node.js Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Continuously rebuilds the SDK for the Node.js platform automatically upon each file save. Use this during development for Node.js-specific changes. ```sh npm run watch:node ``` -------------------------------- ### Manage File Metadata and Associations Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Configures file metadata, tags, and directory paths, and associates the file with a Parse Object. ```javascript // Save file with metadata and tags const imageFile = new Parse.File('photo.jpg', { base64: imageBase64 }, 'image/jpeg'); imageFile.setMetadata({ width: 1920, height: 1080, camera: 'iPhone 15' }); imageFile.setTags({ category: 'vacation', year: '2024' }); imageFile.setDirectory('user-uploads/photos'); // Requires Master Key await imageFile.save({ useMasterKey: true }); console.log('Metadata:', imageFile.metadata()); console.log('Tags:', imageFile.tags()); // Associate file with an object const Photo = Parse.Object.extend('Photo'); const photo = new Photo(); photo.set('name', 'Vacation Photo'); photo.set('image', imageFile); await photo.save(); ``` -------------------------------- ### Login as Another User (Requires Master Key) Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Log in as a different user, typically for administrative purposes. This operation requires the Master Key. ```javascript // Login as another user (requires Master Key) const adminAsUser = await Parse.User.loginAs('targetUserId'); ``` -------------------------------- ### Configure and Monitor Parse.LiveQuery Connection Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Set the LiveQuery server URL and listen for connection events like open, close, and errors. Ensure the server URL is correctly configured for your Parse Server instance. ```javascript // Configure LiveQuery Parse.liveQueryServerURL = 'wss://your-parse-server.com/parse'; // Monitor connection status Parse.LiveQuery.on('open', () => { console.log('LiveQuery connection opened'); }); Parse.LiveQuery.on('close', () => { console.log('LiveQuery connection closed'); }); Parse.LiveQuery.on('error', (error) => { console.error('LiveQuery error:', error); }); ``` -------------------------------- ### Build TypeScript Definitions Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Generates TypeScript definition files (.d.ts) for the SDK. These types are essential for TypeScript users and should not be manually edited. ```sh npm run build:types ``` -------------------------------- ### Run Integration Tests Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Executes integration tests that verify communication with a Parse Server instance. Requires a running MongoDB instance. ```sh npm run integration ``` -------------------------------- ### Include Parse SDK in WeChat Miniprogram Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md For WeChat miniprograms, include the Parse SDK by specifying the 'parse/weapp' path. ```javascript // In a WeChat miniprogram const Parse = require('parse/weapp'); ``` -------------------------------- ### Run Unit Tests with Jest Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Executes all unit tests using Jest. This command is used to verify the functionality of individual components without external dependencies. ```sh npm test ``` -------------------------------- ### Include Parse SDK in Node.js Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md For server-side applications or Node.js command-line tools, include the Parse SDK by specifying the 'parse/node' path. ```javascript // In a node.js environment const Parse = require('parse/node'); ``` -------------------------------- ### Manage Parse Object Relationships Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Demonstrates creating Pointers, many-to-many Relations, and managing arrays of pointers using the Parse JavaScript SDK. ```javascript // Pointer: One-to-one or many-to-one relationship const Post = Parse.Object.extend('Post'); const Comment = Parse.Object.extend('Comment'); const post = new Post(); post.set('title', 'My Blog Post'); await post.save(); const comment = new Comment(); comment.set('text', 'Great post!'); comment.set('post', post); // Pointer to post comment.set('author', Parse.User.current()); // Pointer to user await comment.save(); // Query comments with included pointer data const commentQuery = new Parse.Query('Comment'); commentQuery.equalTo('post', post); commentQuery.include('author'); // Include author data commentQuery.include('post'); // Include post data const comments = await commentQuery.find(); comments.forEach(c => { console.log(`${c.get('author').get('username')}: ${c.get('text')}`); console.log(`On post: ${c.get('post').get('title')}`); }); // Relation: Many-to-many relationship const Book = Parse.Object.extend('Book'); const Author = Parse.Object.extend('Author'); const book = new Book(); book.set('title', 'The Great Novel'); await book.save(); const author1 = new Author({ name: 'John Smith' }); const author2 = new Author({ name: 'Jane Doe' }); await Parse.Object.saveAll([author1, author2]); // Add authors to book's relation const authorsRelation = book.relation('authors'); authorsRelation.add(author1); authorsRelation.add(author2); await book.save(); // Query relation const authorsQuery = authorsRelation.query(); const bookAuthors = await authorsQuery.find(); console.log('Book authors:', bookAuthors.map(a => a.get('name'))); // Output: Book authors: ['John Smith', 'Jane Doe'] // Remove from relation authorsRelation.remove(author2); await book.save(); // Query objects that have a relation to another object const booksQuery = new Parse.Query('Book'); booksQuery.equalTo('authors', author1); const authorBooks = await booksQuery.find(); console.log('Books by John Smith:', authorBooks.map(b => b.get('title'))); // Arrays of Pointers const Tag = Parse.Object.extend('Tag'); const article = new Parse.Object('Article'); const tags = [ new Tag({ name: 'javascript' }), new Tag({ name: 'parse' }), new Tag({ name: 'backend' }) ]; await Parse.Object.saveAll(tags); article.set('title', 'Working with Parse'); article.set('tags', tags); // Array of pointers await article.save(); // Query with array contains const jsArticles = await new Parse.Query('Article') .equalTo('tags', tags[0]) // Articles with 'javascript' tag .include('tags') .find(); // Add/Remove from array atomically article.addUnique('tags', new Tag({ name: 'tutorial' })); article.remove('tags', tags[2]); // Remove 'backend' tag await article.save(); ``` -------------------------------- ### Manage LiveQuery Subscription Lifecycle Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Unsubscribe from real-time events when no longer needed and close all LiveQuery connections. Reopen the connection if necessary. ```javascript // Unsubscribe when done subscription.unsubscribe(); // Close all LiveQuery connections await Parse.LiveQuery.close(); // Reopen connection await Parse.LiveQuery.open(); ``` -------------------------------- ### Watch and Rebuild SDK for React Native Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Continuously rebuilds the SDK for the React Native platform automatically upon each file save. Use this during development for React Native-specific changes. ```sh npm run watch:react-native ``` -------------------------------- ### Link Existing User with Provider Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Associate a third-party identity with the currently logged-in user. ```javascript // Link existing user with provider const currentUserToLink = Parse.User.current(); await currentUserToLink.linkWith('google', { authData: { id: 'google-user-id', id_token: 'google-id-token' } }); ``` -------------------------------- ### Enable IndexedDB Storage in Browser Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md For web worker or browser applications, configure the Parse SDK to use IndexedDB for storage by setting the storage controller. ```javascript Parse.CoreManager.setStorageController(Parse.IndexedDB); ``` -------------------------------- ### Register Multiple Subclasses Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/changelogs/CHANGELOG_release.md Iterate through an array of class names to register them with a custom class. ```javascript const classNames = ['ClassOne', 'ClassTwo', 'ClassThree']; for (const className of classNames) { Parse.Object.registerSubclass(className, CustomClass); } ``` -------------------------------- ### Include Parse SDK in Browser Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md For browser-based applications, include the Parse SDK using a standard require statement or ES6 import. Ensure you are using the correct path for the minified version. ```javascript const Parse = require('parse'); ``` ```javascript // ES6 Minimized import Parse from 'parse/dist/parse.min.js'; ``` -------------------------------- ### Enable Idempotency in Parse SDK Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/changelogs/CHANGELOG_release.md Use these commands to enable experimental idempotency for client requests to prevent duplicate processing due to network issues. ```javascript Parse.CoreManager.set('IDEMPOTENCY', true) ``` ```javascript Parse.idempotency = true ``` -------------------------------- ### Log In with Additional Authentication Data (MFA) Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Log in a user by providing additional authentication data, such as a TOTP code for multi-factor authentication. ```javascript // Log in with additional auth data (MFA) const userWithMFA = await Parse.User.logInWithAdditionalAuth( 'johndoe', 'secretPassword123', { totp: { code: '123456' } } ); ``` -------------------------------- ### Watch for TypeScript Definition Changes Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Continuously rebuilds TypeScript definition files automatically upon each save. Use this during development of type definitions. ```sh npm run watch:ts ``` -------------------------------- ### Log In a User with Parse.User Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Authenticate an existing user using their username and password. Handles potential login failures. ```javascript // Log in with username and password try { const loggedInUser = await Parse.User.logIn('johndoe', 'secretPassword123'); console.log('Logged in as:', loggedInUser.getUsername()); console.log('Email:', loggedInUser.getEmail()); } catch (error) { console.error('Login failed:', error.message); } ``` -------------------------------- ### Include Parse SDK in React Native Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/README.md For React Native applications, include the Parse SDK using 'parse/react-native.js'. For versions 0.50 and above, ensure you set the Async Storage. ```javascript // In a React Native application const Parse = require('parse/react-native.js'); // On React Native >= 0.50 and Parse >= 1.11.0, set the Async const AsyncStorage = require('@react-native-async-storage/async-storage'); Parse.setAsyncStorage(AsyncStorage); ``` -------------------------------- ### Run TypeScript Type Tests Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/CONTRIBUTING.md Executes tests against the generated TypeScript definition files (.d.ts) to ensure type correctness. This verifies that the generated types accurately reflect the SDK's API. ```sh npm run test:types ``` -------------------------------- ### Subscribe with Session Token Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Subscribe to LiveQuery data using a user's session token to access ACL-restricted objects. Ensure a user is currently logged in. ```javascript // Subscribe with session token (for ACL-restricted objects) const secureQuery = new Parse.Query('PrivateMessage'); const secureSubscription = await secureQuery.subscribe( Parse.User.current().getSessionToken() ); ``` -------------------------------- ### Configure Custom Object ID Source: https://github.com/parse-community/parse-sdk-js/blob/alpha/changelogs/CHANGELOG_release.md Enable the ability to save objects with a custom objectId. ```javascript Parse.allowCustomObjectId = true ``` -------------------------------- ### Subscribe to LiveQuery Events Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Subscribe to real-time updates for a specific Parse query. Handles events such as object creation, updates, deletion, and changes in query matching. ```javascript // Subscribe to a query const messageQuery = new Parse.Query('Message'); messageQuery.equalTo('roomId', 'room_123'); messageQuery.descending('createdAt'); const subscription = await messageQuery.subscribe(); // Handle real-time events subscription.on('create', (message) => { console.log('New message:', message.get('text')); console.log('From:', message.get('author').get('username')); }); subscription.on('update', (message) => { console.log('Message updated:', message.id); console.log('New text:', message.get('text')); }); subscription.on('delete', (message) => { console.log('Message deleted:', message.id); }); subscription.on('enter', (message) => { // Object now matches the query (e.g., roomId changed to 'room_123') console.log('Message entered query:', message.id); }); subscription.on('leave', (message) => { // Object no longer matches the query console.log('Message left query:', message.id); }); // Subscription lifecycle events subscription.on('open', () => { console.log('Subscription opened'); }); subscription.on('close', () => { console.log('Subscription closed'); }); ``` -------------------------------- ### Enable Current User in Server Environment (Node.js) Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Enable the `Parse.User.current()` method in a Node.js server environment, which is disabled by default for security reasons. ```javascript // Node.js: Enable current user in server environment Parse.User.enableUnsafeCurrentUser(); ``` -------------------------------- ### Third-Party Authentication (OAuth) Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Log in a user using third-party authentication providers like Facebook, providing necessary auth data. ```javascript // Third-party authentication (OAuth) const userWithFacebook = await Parse.User.logInWith('facebook', { authData: { id: 'facebook-user-id', access_token: 'facebook-access-token', expiration_date: new Date().toISOString() } }); ``` -------------------------------- ### Log Out User Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Terminate the current user's session and log them out. ```javascript // Log out await Parse.User.logOut(); console.log('User logged out, current user:', Parse.User.current()); // Output: User logged out, current user: null ``` -------------------------------- ### Request Password Reset Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Initiate the password reset process by sending an email to the specified address. ```javascript // Password reset await Parse.User.requestPasswordReset('john@example.com'); console.log('Password reset email sent'); ``` -------------------------------- ### Save Object with Location Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Shows how to associate a Parse.GeoPoint with a Parse object and save it to the database. This is essential for performing location-based queries. ```javascript // Save object with location const Restaurant = Parse.Object.extend('Restaurant'); const restaurant = new Restaurant(); restaurant.set('name', 'Best Pizza'); restaurant.set('location', new Parse.GeoPoint(37.7749, -122.4194)); await restaurant.save(); ``` -------------------------------- ### Query Restaurants Near a Point Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Finds restaurants located near a specified geographic point using the `near` constraint. The results are limited to 10 by default. ```javascript // Query: Find restaurants near a point const userLocation = new Parse.GeoPoint(37.7833, -122.4167); const nearbyQuery = new Parse.Query('Restaurant'); nearbyQuery.near('location', userLocation); nearbyQuery.limit(10); const nearbyRestaurants = await nearbyQuery.find(); nearbyRestaurants.forEach(r => { const loc = r.get('location'); const distance = userLocation.milesTo(loc); console.log(`${r.get('name')}: ${distance.toFixed(2)} miles away`); }); // Output: Best Pizza: 0.58 miles away ``` -------------------------------- ### Request Email Verification Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Send an email verification link to a user's registered email address. ```javascript // Email verification await Parse.User.requestEmailVerification('john@example.com'); ``` -------------------------------- ### Query Restaurants Within Radius Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Filters restaurants to find those within a specified radius from a given point. Supports both miles and kilometers. ```javascript // Query: Find within specific radius (miles) const withinMilesQuery = new Parse.Query('Restaurant'); withinMilesQuery.withinMiles('location', userLocation, 5); const within5Miles = await withinMilesQuery.find(); ``` ```javascript // Query: Find within radius (kilometers) const withinKmQuery = new Parse.Query('Restaurant'); withinKmQuery.withinKilometers('location', userLocation, 10); const within10Km = await withinKmQuery.find(); ``` -------------------------------- ### Send Real-time Chat Message Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Function to send a new chat message to a specific room. It creates a new Parse object and saves it, which will then be broadcast via LiveQuery. ```javascript // Send a message async function sendMessage(roomId, text) { const message = new Parse.Object('ChatMessage'); message.set('room', roomId); message.set('text', text); message.set('sender', Parse.User.current()); await message.save(); } ``` -------------------------------- ### Verify Password Without Logging In Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Check if a given username and password combination is correct without establishing a session. ```javascript // Verify password without logging in try { await Parse.User.verifyPassword('johndoe', 'secretPassword123'); console.log('Password is correct'); } catch (error) { console.log('Password is incorrect'); } ``` -------------------------------- ### Parse.Query Data Retrieval Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Methods for querying, filtering, and aggregating data from Parse classes. ```APIDOC ## Parse.Query Operations ### Description Provides capabilities to query, filter, sort, paginate, and aggregate data from Parse objects. ### Methods - **find()**: Retrieves an array of objects matching the query constraints. - **first()**: Retrieves the first object matching the query constraints. - **count()**: Returns the number of objects that match the query. - **distinct(key)**: Returns an array of unique values for a specific key. - **aggregate(pipeline)**: Performs aggregation operations on the query results. ### Query Constraints - **equalTo(key, value)**: Matches objects where the key equals the value. - **greaterThan(key, value)**: Matches objects where the key is greater than the value. - **lessThanOrEqualTo(key, value)**: Matches objects where the key is less than or equal to the value. - **startsWith(key, value)**: Matches string values starting with the provided string. - **contains(key, value)**: Matches string values containing the provided string. - **matches(key, regex)**: Matches string values against a regular expression. - **containsAll(key, array)**: Matches array values containing all elements in the provided array. - **containedIn(key, array)**: Matches values present in the provided array. - **notContainedIn(key, array)**: Matches values not present in the provided array. - **matchesQuery(key, query)**: Performs a subquery on a relational field. ### Pagination and Sorting - **limit(number)**: Limits the number of results returned. - **skip(number)**: Skips a number of results for pagination. - **descending(key)**: Sorts results by key in descending order. ### Compound Queries - **Parse.Query.or(query1, query2)**: Returns a query that is the logical OR of the provided queries. ``` -------------------------------- ### Manage Parse ACLs Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Control read and write permissions for Parse objects at user and role levels. Set public access, specific user access, or role-based access. Default ACLs can also be configured. ```javascript // Create ACL for current user only const privateACL = new Parse.ACL(Parse.User.current()); console.log('User can read:', privateACL.getReadAccess(Parse.User.current())); console.log('User can write:', privateACL.getWriteAccess(Parse.User.current())); // Output: User can read: true // Output: User can write: true // Create object with private ACL const privateNote = new Parse.Object('Note'); privateNote.set('content', 'My private note'); privateNote.setACL(privateACL); await privateNote.save(); // Create public read, private write ACL const publicReadACL = new Parse.ACL(); publicReadACL.setPublicReadAccess(true); publicReadACL.setPublicWriteAccess(false); publicReadACL.setWriteAccess(Parse.User.current(), true); const blogPost = new Parse.Object('BlogPost'); blogPost.set('title', 'My Public Blog Post'); blogPost.setACL(publicReadACL); await blogPost.save(); // Role-based ACL const roleACL = new Parse.ACL(); roleACL.setPublicReadAccess(true); roleACL.setRoleWriteAccess('Admin', true); roleACL.setRoleReadAccess('Moderator', true); roleACL.setRoleWriteAccess('Moderator', true); const moderatedContent = new Parse.Object('Content'); moderatedContent.set('text', 'Admin and moderator can edit'); moderatedContent.setACL(roleACL); await moderatedContent.save(); // Set default ACL for all new objects const defaultACL = new Parse.ACL(); defaultACL.setPublicReadAccess(true); Parse.ACL.setDefaultACL(defaultACL, true); // true = include current user // Check permissions const acl = new Parse.ACL(); acl.setReadAccess('userId123', true); acl.setWriteAccess('userId123', false); acl.setRoleReadAccess('Editor', true); console.log('User userId123 can read:', acl.getReadAccess('userId123')); console.log('User userId123 can write:', acl.getWriteAccess('userId123')); console.log('Editors can read:', acl.getRoleReadAccess('Editor')); console.log('Public can read:', acl.getPublicReadAccess()); // Output: User userId123 can read: true // Output: User userId123 can write: false // Output: Editors can read: true // Output: Public can read: false // Create a Role const roleACLForRole = new Parse.ACL(); roleACLForRole.setPublicReadAccess(true); const adminRole = new Parse.Role('Admin', roleACLForRole); adminRole.getUsers().add(Parse.User.current()); await adminRole.save(); // Add users to role const userToAdd = await new Parse.Query(Parse.User).get('userId456'); adminRole.getUsers().add(userToAdd); await adminRole.save(); // Create role hierarchy (Editor role inherits from Admin) const editorRole = new Parse.Role('Editor', roleACLForRole); editorRole.getRoles().add(adminRole); await editorRole.save(); ``` -------------------------------- ### Cancel File Operations Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Aborts an ongoing file upload or download request. ```javascript // Cancel ongoing upload/download parseFile.save(); parseFile.cancel(); // Aborts the request ``` -------------------------------- ### Query Restaurants Within Polygon Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Identifies restaurants situated within a custom polygon defined by an array of GeoPoint objects. ```javascript // Query: Find within polygon const polygon = [ new Parse.GeoPoint(37.7, -122.5), new Parse.GeoPoint(37.9, -122.5), new Parse.GeoPoint(37.9, -122.3), new Parse.GeoPoint(37.7, -122.3) ]; const polygonQuery = new Parse.Query('Restaurant'); polygonQuery.withinPolygon('location', polygon); const inPolygon = await polygonQuery.find(); ``` -------------------------------- ### Handle Parse SDK Errors Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Use a switch statement on error.code to handle specific Parse error types. Batch operations require checking for Parse.Error.AGGREGATE_ERROR to inspect individual object failures. ```javascript // Comprehensive error handling try { const user = await Parse.User.logIn('username', 'wrongpassword'); } catch (error) { // error.code contains the Parse error code // error.message contains a human-readable message switch (error.code) { case Parse.Error.OBJECT_NOT_FOUND: console.error('User not found'); break; case Parse.Error.INVALID_SESSION_TOKEN: console.error('Session expired, please log in again'); await Parse.User.logOut(); break; case Parse.Error.CONNECTION_FAILED: console.error('Network connection failed'); break; case Parse.Error.TIMEOUT: console.error('Request timed out'); break; case Parse.Error.USERNAME_MISSING: console.error('Username is required'); break; case Parse.Error.PASSWORD_MISSING: console.error('Password is required'); break; case Parse.Error.USERNAME_TAKEN: console.error('Username is already taken'); break; case Parse.Error.EMAIL_TAKEN: console.error('Email is already registered'); break; case Parse.Error.EMAIL_NOT_FOUND: console.error('Email not found'); break; case Parse.Error.INVALID_EMAIL_ADDRESS: console.error('Invalid email format'); break; case Parse.Error.DUPLICATE_VALUE: console.error('Duplicate value for unique field'); break; case Parse.Error.INVALID_QUERY: console.error('Invalid query'); break; case Parse.Error.INVALID_ACL: console.error('Invalid ACL'); break; case Parse.Error.OPERATION_FORBIDDEN: console.error('Operation not allowed'); break; case Parse.Error.SCRIPT_FAILED: console.error('Cloud Code script failed'); break; case Parse.Error.VALIDATION_ERROR: console.error('Validation error:', error.message); break; default: console.error('Error:', error.code, error.message); } } // Error handling for batch operations try { const objects = [/* ... */]; await Parse.Object.saveAll(objects); } catch (error) { // For batch operations, check individual errors if (error.code === Parse.Error.AGGREGATE_ERROR) { error.errors.forEach((e, index) => { console.error(`Object ${index} failed:`, e.message); }); } } // Retry logic with exponential backoff async function saveWithRetry(object, maxRetries = 3) { for (let attempt = 1; attempt <= maxRetries; attempt++) { try { return await object.save(); } catch (error) { if (error.code === Parse.Error.CONNECTION_FAILED && attempt < maxRetries) { const delay = Math.pow(2, attempt) * 1000; console.log(`Retry ${attempt}/${maxRetries} in ${delay}ms`); await new Promise(resolve => setTimeout(resolve, delay)); } else { throw error; } } } } ``` -------------------------------- ### Query Restaurants Within GeoBox Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Finds restaurants located within a rectangular geographic bounding box defined by southwest and northeast corner points. ```javascript // Query: Find within bounding box const southwest = new Parse.GeoPoint(37.7, -122.5); const northeast = new Parse.GeoPoint(37.9, -122.3); const boxQuery = new Parse.Query('Restaurant'); boxQuery.withinGeoBox('location', southwest, northeast); const inBox = await boxQuery.find(); ``` -------------------------------- ### Manage ParseObject Data Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Perform CRUD operations and batch processing on Parse objects. Use atomic increments and pointer inclusion for efficient data handling. ```javascript // Create and save a new object const GameScore = Parse.Object.extend('GameScore'); const gameScore = new GameScore(); gameScore.set('score', 1337); gameScore.set('playerName', 'Sean Plott'); gameScore.set('cheatMode', false); try { const result = await gameScore.save(); console.log('Object saved with objectId:', result.id); // Output: Object saved with objectId: xWMyZ4YEGZ } catch (error) { console.error('Error saving object:', error.message); } // Save with specific options await gameScore.save(null, { useMasterKey: true, // Use master key (Node.js only) sessionToken: 'r:abc123', // Use specific session context: { notifyUsers: true } // Pass context to Cloud Code triggers }); // Retrieve an object by ID const query = new Parse.Query(GameScore); const fetchedScore = await query.get('xWMyZ4YEGZ'); console.log('Score:', fetchedScore.get('score')); // Output: Score: 1337 // Update an object fetchedScore.set('score', 1500); fetchedScore.increment('gamesPlayed'); // Atomic increment await fetchedScore.save(); // Delete an object await fetchedScore.destroy(); // Batch save multiple objects const objects = [ new GameScore({ score: 100, playerName: 'Player1' }), new GameScore({ score: 200, playerName: 'Player2' }), new GameScore({ score: 300, playerName: 'Player3' }) ]; await Parse.Object.saveAll(objects); // Fetch with included pointers const post = await new Parse.Query('Post') .include('author') .include('comments.author') .get('postId123'); console.log('Author name:', post.get('author').get('name')); ``` -------------------------------- ### Call Parse Cloud Functions Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Execute server-side Cloud Functions with optional parameters and execution options. Handles results and errors. ```javascript // Call a cloud function try { const result = await Parse.Cloud.run('hello', { name: 'World' }); console.log('Cloud function result:', result); // Output: Cloud function result: Hello, World! } catch (error) { console.error('Cloud function error:', error.message); } // Call with options const secureResult = await Parse.Cloud.run('sensitiveOperation', { data: 'secret' }, { useMasterKey: true, // Node.js only sessionToken: 'r:abc123', // Use specific session context: { source: 'mobile-app' } // Pass to triggers } ); // Complex cloud function call const orderResult = await Parse.Cloud.run('processOrder', { items: [ { productId: 'prod_123', quantity: 2 }, { productId: 'prod_456', quantity: 1 } ], shippingAddress: { street: '123 Main St', city: 'San Francisco', state: 'CA', zip: '94102' }, paymentMethod: 'card_abc123' }); console.log('Order ID:', orderResult.orderId); console.log('Total:', orderResult.total); ``` -------------------------------- ### Calculate Distances Between GeoPoints Source: https://context7.com/parse-community/parse-sdk-js/llms.txt Computes the distance between two Parse.GeoPoint objects in miles, kilometers, or radians. Useful for displaying travel distances or proximity information. ```javascript // Calculate distances between points const sf = new Parse.GeoPoint(37.7749, -122.4194); const la = new Parse.GeoPoint(34.0522, -118.2437); console.log('Distance (miles):', sf.milesTo(la).toFixed(2)); console.log('Distance (km):', sf.kilometersTo(la).toFixed(2)); console.log('Distance (radians):', sf.radiansTo(la).toFixed(4)); // Output: Distance (miles): 347.42 // Output: Distance (km): 559.12 // Output: Distance (radians): 0.0877 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.