### Initialize Local Development Environment Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Commands to clone the repository, install dependencies, and start the development watch process. ```sh $ git clone https://github.com/parse-community/parse-server $ cd parse-server # go into the clone directory $ npm install # install all the node dependencies $ code . # launch vscode $ npm run watch # run babel watching for local file changes ``` -------------------------------- ### Install and Run Parse Server Locally Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Commands to install Parse Server and MongoDB runner globally, start the database, and launch the server. ```bash $ npm install -g parse-server mongodb-runner $ mongodb-runner start $ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://localhost/test ``` -------------------------------- ### Run GraphQL API via CLI Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Installs dependencies and starts the Parse Server with GraphQL and Playground enabled. ```bash $ npm install -g parse-server mongodb-runner $ mongodb-runner start $ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://localhost/test --publicServerURL http://localhost:1337/parse --mountGraphQL --mountPlayground ``` -------------------------------- ### Add Setup Script to Dockerfile Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Copies a database setup script into the Docker image's initialization directory and makes it executable. This script runs only when the container is initialized with an empty database. ```dockerfile #Install additional scripts. These are run in abc order during initial start COPY ./scripts/setup-dbs.sh /docker-entrypoint-initdb.d/setup-dbs.sh RUN chmod +x /docker-entrypoint-initdb.d/setup-dbs.sh ``` -------------------------------- ### Initialize Parse Server with GraphQL configuration Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Command to start Parse Server with custom schema and cloud code paths. ```bash $ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://localhost/test --publicServerURL http://localhost:1337/parse --cloud ./cloud/main.js --graphQLSchema ./cloud/schema.graphql --mountGraphQL --mountPlayground ``` -------------------------------- ### Parse Server 5 Initialization and Mounting Source: https://github.com/parse-community/parse-server/blob/alpha/6.0.0.md This example shows the previous method of initializing and mounting Parse Server in Parse Server 5, where the server could be mounted before it was fully ready, potentially leading to undefined behavior. ```javascript // 1. Import Parse Server const { ParseServer } = require('parse-server'); // 2. Create a Parse Server instance as express middleware const server = new ParseServer(config); // 3. Mount express middleware app.use("/parse", server); ``` -------------------------------- ### Installations API Endpoints Source: https://github.com/parse-community/parse-server/wiki/installations.js This section covers the core API endpoints for interacting with Parse Server installations. ```APIDOC ## POST /installations/ ### Description Creates a new installation. ### Method POST ### Endpoint /installations/ ## GET /installations/ ### Description Retrieves a list of installations. ### Method GET ### Endpoint /installations/ ## GET /installations/:objectId ### Description Retrieves a specific installation by its object ID. ### Method GET ### Endpoint /installations/:objectId ### Parameters #### Path Parameters - **objectId** (string) - Required - The unique identifier of the installation to retrieve. ## PUT /installations/:objectId ### Description Updates an existing installation by its object ID. ### Method PUT ### Endpoint /installations/:objectId ### Parameters #### Path Parameters - **objectId** (string) - Required - The unique identifier of the installation to update. ## DELETE /installations/:objectId ### Description Deletes a specific installation by its object ID. ### Method DELETE ### Endpoint /installations/:objectId ### Parameters #### Path Parameters - **objectId** (string) - Required - The unique identifier of the installation to delete. ``` -------------------------------- ### Build and Run Parse Server with Docker Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Commands to clone the repository, build the Docker image, and start a MongoDB container. ```bash $ git clone https://github.com/parse-community/parse-server $ cd parse-server $ docker build --tag parse-server . $ docker run --name my-mongo -d mongo ``` -------------------------------- ### Start Express Application and MongoDB Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Commands to start the MongoDB runner and the Node.js application for Parse Server and Express.js. ```bash $ npx mongodb-runner start $ node index.js ``` -------------------------------- ### Parse Server 6 Asynchronous Initialization and Mounting Source: https://github.com/parse-community/parse-server/blob/alpha/6.0.0.md Demonstrates the required asynchronous startup process for Parse Server 6. The server must be started with `server.start()` before being mounted using `server.app` to ensure it's ready to receive requests. ```javascript // 1. Import Parse Server const ParseServer = require('parse-server'); // 2. Create a Parse Server instance const server = new ParseServer(config); // 3. Start up Parse Server asynchronously await server.start(); // 4. Mount express middleware app.use("/parse", server.app); ``` -------------------------------- ### Create and Get Files with GridStoreAdapter Source: https://github.com/parse-community/parse-server/wiki/GridStoreAdapter.js Use the `create` method to store a file and the `get` method to retrieve it. These operations are asynchronous and return Promises. ```javascript gridstore.create(config, filename, data).then( ... ); ``` ```javascript gridstore.get(config, filename).then( ... ); ``` -------------------------------- ### Example Directory Structure for Localization Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Illustrates the recommended directory structure for storing HTML pages and JSON translation resources. ```javascript root/ ├── public/ // pages base path │ ├── example.html // the page containing placeholders ├── private/ // folder outside of public scope │ └── translations.json // JSON resource file ``` -------------------------------- ### Example Subscribe Message for Event Handling Source: https://github.com/parse-community/parse-server/wiki/Parse-LiveQuery-Protocol-Specification An example of a subscribe message used to demonstrate the types of events that can be received from the LiveQuery server. ```javascript { "op": "subscribe", "requestId": 1, "query": { "className": "Player", "where": {"name": "test"} } } ``` -------------------------------- ### Install Parse Server and Express Dependencies Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Installs the necessary npm packages for a Parse Server application integrated with Express.js. ```bash $ mkdir my-app $ cd my-app $ npm install parse-server express --save ``` -------------------------------- ### GraphQL Create Class Response Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Example JSON response after successfully creating a 'GameScore' class using the `createClass` mutation. ```json { "data": { "createClass": { "name": "GameScore", "schemaFields": [ { "name": "objectId", "__typename": "SchemaStringField" }, { "name": "updatedAt", "__typename": "SchemaDateField" }, { "name": "createdAt", "__typename": "SchemaDateField" }, { "name": "playerName", "__typename": "SchemaStringField" }, { "name": "score", "__typename": "SchemaNumberField" }, { "name": "cheatMode", "__typename": "SchemaBooleanField" }, { "name": "ACL", "__typename": "SchemaACLField" } ] } } } ``` -------------------------------- ### Example Push Message Source: https://github.com/parse-community/parse-server/wiki/PPNS-Protocol-Specification A sample push notification message formatted as a single line of compacted JSON. ```json {"data":{"alert":"demo push 1"},"push_id":"ZX1JVl5ael","time":"2016-02-16T22:00:00.000Z"} ``` -------------------------------- ### Define Parse Server Git Dependency Source: https://github.com/parse-community/parse-server/blob/alpha/changelogs/CHANGELOG_release.md Example of a dependency definition that points to a specific Git tag for Parse Server. ```json "parse-server": "git@github.com:parse-community/parse-server.git#4.9.3" ``` -------------------------------- ### Parse Server Localization Configuration with Custom URLs Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Example Parse Server configuration enabling localization and setting custom URLs for pages. Note that custom URLs may disable localization for feature pages. ```javascript const api = new ParseServer({ ...otherOptions, pages: { enableLocalization: true, customUrls: { passwordReset: 'https://example.com/page.html' } } } ``` -------------------------------- ### Configuring File Adapters Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Parse Server supports multiple file storage adapters. The default is GridFSBucketAdapter. Other options include S3Adapter, GCSAdapter, and FSAdapter. Configuration for S3, GCS, and FSAdapter requires additional setup detailed in the Parse Server guide. ```APIDOC ## Configuring File Adapters Parse Server allows developers to choose from several options when hosting files: - `GridFSBucketAdapter` - which is backed by MongoDB - `S3Adapter` - which is backed by [Amazon S3](https://aws.amazon.com/s3/) - `GCSAdapter` - which is backed by [Google Cloud Storage](https://cloud.google.com/storage/) - `FSAdapter` - local file storage `GridFSBucketAdapter` is used by default and requires no setup, but if you're interested in using Amazon S3, Google Cloud Storage, or local file storage, additional configuration information is available in the [Parse Server guide](http://docs.parseplatform.org/parse-server/guide/#configuring-file-adapters). ### Restricting File URL Domains Parse objects can reference files by URL. To prevent [SSRF attacks](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery) via crafted file URLs, you can restrict the allowed URL domains using the `fileUpload.allowedFileUrlDomains` option. This protects against scenarios where an attacker provides a `Parse.File` with an arbitrary URL, for example as a Cloud Function parameter or in a field of type `Object` or `Array`. If Cloud Code or a client calls `getData()` on such a file, the Parse SDK makes an HTTP request to that URL, potentially leaking the server or client IP address and accessing internal services. > [!NOTE] > Fields of type `Parse.File` in the Parse schema are not affected by this attack, because Parse Server discards the URL on write and dynamically generates it on read based on the file adapter configuration. ```javascript const parseServer = new ParseServer({ ...otherOptions, fileUpload: { allowedFileUrlDomains: ['cdn.example.com', '*.example.com'], }, }); ``` | Parameter | Optional | Type | Default | Environment Variable | |---|---|---|---|---| | `fileUpload.allowedFileUrlDomains` | yes | `String[]` | `['*']` | `PARSE_SERVER_FILE_UPLOAD_ALLOWED_FILE_URL_DOMAINS` | - `['*']` (default) allows file URLs with any domain. - `['cdn.example.com']` allows only exact hostname matches. - `['*.example.com']` allows any subdomain of `example.com`. - `[]` blocks all file URLs; only files referenced by name are allowed. ``` -------------------------------- ### Basic Configuration Options Source: https://github.com/parse-community/parse-server/blob/alpha/README.md These are the fundamental options required or recommended for initializing Parse Server. ```APIDOC ## Basic Options ### Parameters - **appId** (string) - Required - The application id for the server instance. - **masterKey** (string) - Required - The master key for overriding ACL security. - **databaseURI** (string) - Required - The connection string for your database (e.g., `mongodb://user:pass@host.com/dbname`). Ensure passwords with special characters are URL encoded. - **port** (number) - Optional - The port for the server to listen on. Defaults to 1337. - **serverURL** (string) - Optional - The URL of your Parse Server (e.g., `http://localhost:1337/parse`). Used for Cloud Code requests. - **cloud** (string) - Optional - The absolute path to your Cloud Code `main.js` file. - **push** (object) - Optional - Configuration options for APNS and FCM push notifications. ``` -------------------------------- ### Initialize and mount Parse Server Source: https://context7.com/parse-community/parse-server/llms.txt Configures a Parse Server instance with database, security, and adapter settings, then mounts it onto an Express application. ```javascript const express = require('express'); const { ParseServer } = require('parse-server'); const app = express(); const server = new ParseServer({ // Core configuration databaseURI: process.env.DATABASE_URI || 'mongodb://localhost:27017/myapp', appId: process.env.APP_ID || 'myAppId', masterKey: process.env.MASTER_KEY || 'myMasterKey', serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', publicServerURL: process.env.PUBLIC_SERVER_URL || 'http://localhost:1337/parse', // Cloud Code cloud: './cloud/main.js', // Security allowClientClassCreation: false, enableAnonymousUsers: true, // File storage (S3 example) filesAdapter: { module: '@parse/s3-files-adapter', options: { bucket: 'my-bucket', region: 'us-east-1' } }, // Email adapter verifyUserEmails: true, emailVerifyTokenValidityDuration: 2 * 60 * 60, // 2 hours emailAdapter: { module: 'parse-server-api-mail-adapter', options: { sender: 'noreply@example.com', templates: { passwordResetEmail: { /* ... */ }, verificationEmail: { /* ... */ } } } }, // Password policy passwordPolicy: { validatorPattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/, doNotAllowUsername: true, maxPasswordHistory: 5 }, // Account lockout accountLockout: { duration: 5, threshold: 5, unlockOnPasswordReset: true }, // LiveQuery liveQuery: { classNames: ['Message', 'Notification'] } }); // Start the server await server.start(); // Mount on Express app.use('/parse', server.app); // Start listening const httpServer = app.listen(1337, () => { console.log('Parse Server running on port 1337'); }); // Graceful shutdown process.on('SIGTERM', async () => { console.log('Shutting down...'); await server.handleShutdown(); httpServer.close(); }); ``` -------------------------------- ### GET /files/:fileName Source: https://github.com/parse-community/parse-server/wiki/files.js Retrieves a specific file from the server by its filename. ```APIDOC ## GET /files/:fileName ### Description Retrieves a file stored in the Parse Server system. ### Method GET ### Endpoint /files/:fileName ### Parameters #### Path Parameters - **fileName** (string) - Required - The name of the file to retrieve. ``` -------------------------------- ### Initialize and execute a RestQuery Source: https://github.com/parse-community/parse-server/wiki/RestQuery.js Instantiate a RestQuery with configuration and authentication details, then use the execute method to perform the query. ```javascript var query = new RestQuery(config, auth, className, restWhere, restOptions); // A convenient method to perform all the steps of processing a query // in order. // Returns a promise for the response - an object with optional keys // 'results' and 'count'. query.execute().then( ... ); ``` -------------------------------- ### GET /parse/health Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Check the current health status of the Parse Server instance. ```APIDOC ## GET /parse/health ### Description Check the Parse Server health by sending a request to the /parse/health endpoint. ### Method GET ### Endpoint /parse/health ### Response #### Success Response (200) - **status** (string) - The current status of the server (initialized, starting, ok, error). #### Response Example { "status": "ok" } ``` -------------------------------- ### Initialize Parse Server with Express Source: https://github.com/parse-community/parse-server/wiki/index.js Use the ParseServer constructor to create an instance that can be mounted onto an Express application. Configure essential parameters like appId, masterKey, and the path to your cloud code. ```javascript // ParseServer works like a constructor of an express app. // The args that we understand are: // "databaseAdapter": a class like ExportAdapter providing create, find, // update, and delete // "filesAdapter": a class like GridStoreAdapter providing create, get, // and delete // "databaseURI": a uri like mongodb://localhost:27017/dbname to tell us // what database this Parse API connects to. // "cloud": relative location to cloud code to require // "appId": the application id to host // "masterKey": the master key for requests to this app // "collectionPrefix": optional prefix for database collection names // "fileKey": optional key from Parse dashboard for supporting older files // hosted by Parse // "clientKey": optional key from Parse dashboard // "dotNetKey": optional key from Parse dashboard // "restAPIKey": optional key from Parse dashboard // "javascriptKey": optional key from Parse dashboard var ParseServer = require('parse-server').ParseServer; var api = new ParseServer({ appId: 'my-app-id', masterKey: 'secret', cloud: './cloud/main.js' }); myExpressApp.use('/parse', api); ``` -------------------------------- ### Run Local Benchmarks Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Executes performance benchmarks locally. Use 'benchmark:quick' for a faster test with fewer iterations or 'benchmark' for a comprehensive test with a higher iteration count. ```bash npm run benchmark:quick # Quick test with 10 iterations ``` ```bash npm run benchmark # Full test with 10,000 iterations ``` -------------------------------- ### Initialize and Execute RestWrite Source: https://github.com/parse-community/parse-server/wiki/RestWrite.js Instantiate a RestWrite object with configuration and data, then execute the operation to process the database write. ```javascript // query and data are both provided in REST API format. So data // types are encoded by plain old objects. // If query is null, this is a "create" and the data in data should be // created. // Otherwise this is an "update" - the object matching the query // should get updated with data. // RestWrite will handle objectId, createdAt, and updatedAt for // everything. It also knows to use triggers and special modifications // for the _User class. var write = new RestWrite(config, auth, className, query, data, originalData); // A convenient method to perform all the steps of processing the // write, in order. // Returns a promise for a {response, status, location} object. // status and location are optional. write.execute().then( ... ); ``` -------------------------------- ### Example PPNS Connection Transcript Source: https://github.com/parse-community/parse-server/wiki/PPNS-Protocol-Specification This transcript illustrates the sequence of messages exchanged between a client and the PPNS server during a connection. It includes handshake, push notifications, and ping/pong messages. ```json < {"installation_id":"7091d74b-9fd6-4af5-92d6-7064bb4df82a","oauth_key":"nfFNZULwvK2PJnkfeGE22hapc55LopZA7XFKrXPl","v":"e1.0.0","last":"2016-02-08T01:00:30.123Z"} ``` ```json > {"data":{"alert":"queued push 1"},"push_id":"HT4puYKYjU","time":"2016-02-07T22:00:00.000Z"} ``` ```json > {"data":{"alert":"push 2"},"push_id":"8RkhQGHCtd","time":"2016-02-10T03:00:00.000Z"} ``` ```json < {} ``` ```json > {} ``` ```json > {"data":{"alert":"push 3"},"push_id":"mz7VAt6YtS","time":"2016-02-10T22:10:30.000Z"} ``` ```json < {} ``` -------------------------------- ### Implement LiveQuery Real-time Subscriptions Source: https://context7.com/parse-community/parse-server/llms.txt Configures server-side LiveQuery support and demonstrates client-side event handling for real-time data updates. ```javascript // Server configuration with LiveQuery const server = new ParseServer({ databaseURI: 'mongodb://localhost:27017/myapp', appId: 'MY_APP_ID', masterKey: 'MY_MASTER_KEY', serverURL: 'http://localhost:1337/parse', liveQuery: { classNames: ['Message', 'Notification', 'GameState'] } }); // Client-side subscription const query = new Parse.Query('Message'); query.equalTo('conversationId', 'abc123'); const subscription = await query.subscribe(); subscription.on('create', (message) => { console.log('New message:', message.get('text')); appendMessageToUI(message); }); subscription.on('update', (message) => { console.log('Message updated:', message.id); updateMessageInUI(message); }); subscription.on('delete', (message) => { console.log('Message deleted:', message.id); removeMessageFromUI(message); }); subscription.on('enter', (message) => { // Object now matches the query (e.g., was edited to match) console.log('Message entered query:', message.id); }); subscription.on('leave', (message) => { // Object no longer matches the query console.log('Message left query:', message.id); }); // Server-side LiveQuery trigger Parse.Cloud.afterLiveQueryEvent('Message', (request) => { // Filter or modify events before sending to clients if (request.event === 'create') { const message = request.object; // Don't send events for system messages if (message.get('isSystemMessage')) { request.sendEvent = false; } } }); ``` -------------------------------- ### Run Parse Server Docker Image Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Launches a Parse Server instance using Docker, linking it to a MongoDB instance and exposing the GraphQL API. Includes options for mounting Cloud Code and the GraphQL Playground. ```bash $ docker run --name my-parse-server --link my-mongo:mongo -v config-vol:/parse-server/config -p 1337:1337 -d parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://mongo/test --publicServerURL http://localhost:1337/parse --mountGraphQL --mountPlayground ``` -------------------------------- ### Initialize and Retrieve Auth Objects Source: https://github.com/parse-community/parse-server/wiki/Auth.js Instantiate an Auth object or use static helper methods to retrieve Auth instances based on master status, session tokens, or unauthenticated states. ```javascript var auth = new Auth(config, isMaster, userObject); var nobody = Auth.nobody(config); var master = Auth.master(config); var sessionAuth = Auth.getAuthForSessionToken(config, sessionToken); ``` -------------------------------- ### Configure Git for HTTPS Protocol Source: https://github.com/parse-community/parse-server/blob/alpha/6.0.0.md Use this command to configure git to use the HTTPS protocol instead of SSH for GitHub dependencies, which can resolve installation issues with Node 14 and npm package lock file version 2. ```bash sudo git config --system url."https://github".insteadOf "ssh://git@github" ``` -------------------------------- ### Mount Parse Server on Express Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Initializes a Parse Server instance and mounts it to an Express application. Ensure the masterKey is kept secure and the databaseURI points to a valid MongoDB instance. ```javascript const express = require('express'); const ParseServer = require('parse-server').ParseServer; const app = express(); const server = new ParseServer({ databaseURI: 'mongodb://localhost:27017/dev', // Connection string for your MongoDB database cloud: './cloud/main.js', // Path to your Cloud Code appId: 'myAppId', masterKey: 'myMasterKey', // Keep this key secret! fileKey: 'optionalFileKey', serverURL: 'http://localhost:1337/parse', // Don't forget to change to https if needed }); // Start server await server.start(); // Serve the Parse API on the /parse URL prefix app.use('/parse', server.app); app.listen(1337, function () { console.log('parse-server-example running on port 1337.'); }); ``` -------------------------------- ### Configure server.js for Parse Dashboard Source: https://github.com/parse-community/parse-server/wiki/Running-Parse-Dashboard-with-HyperDev Initializes the Parse Dashboard with environment variables and mounts it to the Express application. ```javascript var express = require('express'); var ParseDashboard = require('parse-dashboard'); var http = require('http'); var dashboard = new ParseDashboard({ apps: [ { appId: process.env.APP_ID, masterKey: process.env.MASTER_KEY, serverURL: process.env.SERVER_URL, appName: process.env.APP_NAME, }, ], users: [ { user: process.env.USER_NAME, pass: process.env.PASSWORD } ] }, true /* note: you seem to have to set allowInsecureHTTP=true, perhaps HyperDev sites are behind an HTTPS load balancer or proxy with early SSL termination? */); var app = express(); // make the Parse Dashboard available at / app.use('/', dashboard); var port = process.env.PORT || 4040; var httpServer = http.createServer(app); httpServer.listen(port, function () { console.log('parse-dashboard running on port ' + port + '.'); }); ``` -------------------------------- ### Run Postgres with PostGIS Docker Container Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Launches a Docker container for PostgreSQL with PostGIS support, creates a database, and enables necessary extensions. Ensure the container is running before proceeding. ```bash docker run -d --name parse-postgres -p 5432:5432 -e POSTGRES_PASSWORD=password --rm postgis/postgis:17-3.5-alpine && sleep 20 && docker exec -it parse-postgres psql -U postgres -c 'CREATE DATABASE parse_server_postgres_adapter_test_database;' && docker exec -it parse-postgres psql -U postgres -c 'CREATE EXTENSION pgcrypto; CREATE EXTENSION postgis;' -d parse_server_postgres_adapter_test_database && docker exec -it parse-postgres psql -U postgres -c 'CREATE EXTENSION postgis_topology;' -d parse_server_postgres_adapter_test_database ``` -------------------------------- ### Connect to LiveQuery Server Source: https://github.com/parse-community/parse-server/wiki/Parse-LiveQuery-Protocol-Specification Send this message after establishing a WebSocket connection to initiate communication with the LiveQuery server. It includes authentication and identification details. ```javascript { "op": "connect", "applicationId": "", "restAPIKey": "", // Optional "javascriptKey": "", // Optional "clientKey": "", //Optional "windowsKey": "", //Optional "masterKey": "", // Optional "sessionToken": "", // Optional "installationId": "" // Optional } ``` -------------------------------- ### Parse Server Configuration for Static Placeholders Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Configures static key-value pairs as dynamic placeholders for use in HTML pages. These are independent of localization settings. ```javascript const api = new ParseServer({ ...otherOptions, pages: { placeholders: { exampleKey: 'exampleValue' } } } ``` -------------------------------- ### Execute custom GraphQL query Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Runs the custom 'hello' query defined in the schema. ```graphql query { hello } ``` -------------------------------- ### Configure Parse Server with Express.js Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Sets up a Parse Server instance and a Parse GraphQL Server within an Express.js application. Mounts the REST API, GraphQL API, and optionally the GraphQL Playground. ```javascript const express = require('express'); const { ParseServer, ParseGraphQLServer } = require('parse-server'); const app = express(); const parseServer = new ParseServer({ databaseURI: 'mongodb://localhost:27017/test', appId: 'APPLICATION_ID', masterKey: 'MASTER_KEY', serverURL: 'http://localhost:1337/parse', publicServerURL: 'http://localhost:1337/parse', }); const parseGraphQLServer = new ParseGraphQLServer(parseServer, { graphQLPath: '/graphql', playgroundPath: '/playground', }); app.use('/parse', parseServer.app); // (Optional) Mounts the REST API parseGraphQLServer.applyGraphQL(app); // Mounts the GraphQL API parseGraphQLServer.applyPlayground(app); // (Optional) Mounts the GraphQL Playground - do NOT use in Production await parseServer.start(); app.listen(1337, function () { console.log('REST API running on http://localhost:1337/parse'); console.log('GraphQL API running on http://localhost:1337/graphql'); console.log('GraphQL Playground running on http://localhost:1337/playground'); }); ``` -------------------------------- ### Run project test coverage Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Execute this command to obtain the current test coverage report for the project. ```bash npm run coverage ``` -------------------------------- ### Log and Query with FileLoggerAdapter Source: https://github.com/parse-community/parse-server/wiki/FileLoggerAdapter.js Use these methods to record log entries and retrieve historical logs from the file system. ```javascript fileLogger.info('info content', {} => {...}); fileLogger.info('error content', {} => {...}); fileLogger.query({ level: 'error', size: 10, from: Date.now() - (30 * 24 * 60 * 60 * 1000), until: Date.now(), order: 'desc' }, {} => {...}) ``` -------------------------------- ### Verify deployment logs Source: https://github.com/parse-community/parse-server/wiki/Running-Parse-Dashboard-with-HyperDev Expected output in the HyperDev logs upon successful application deployment. ```text Launching node server.js parse-dashboard running on port 3000. ``` -------------------------------- ### Register Benchmark in Suite Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Adds a new benchmark function to the main benchmark suite. Ensure database cleanup is performed before running the benchmark to maintain consistent test conditions. ```javascript console.error('Running New Feature benchmark...'); await cleanupDatabase(); results.push(await benchmarkNewFeature()); ``` -------------------------------- ### User Session Caching Operations Source: https://github.com/parse-community/parse-server/wiki/cache.js Demonstrates how to interact with the user session cache during a request, login, signup, and logout. Ensure the cache is initialized before use. ```javascript var user = cache.getUser(sessionToken); if (!user) { ... } // during login/signup cache.setUser(sessionToken, userObject); // during logout cache.clearUser(sessionToken); ``` -------------------------------- ### Run tests against Postgres Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Execute tests using a specific PostgreSQL connection URI. ```bash PARSE_SERVER_TEST_DB=postgres PARSE_SERVER_TEST_DATABASE_URI=postgres://postgres:password@localhost:5432/parse_server_postgres_adapter_test_database npm run testonly ``` -------------------------------- ### Lint project code Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Run the linter to ensure code compliance before CI submission. ```bash npm run lint ``` -------------------------------- ### Parse Server Configuration for Dynamic Placeholders Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Enables dynamic placeholder values by providing an async function that can access parameters like locale. The function should return an object of key-value pairs. ```javascript const api = new ParseServer({ ...otherOptions, pages: { placeholders: async (params) => { const value = await doSomething(params.locale); return { exampleKey: value }; } } } ``` -------------------------------- ### Client Key Options Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Options to maintain compatibility with older clients by requiring specific client keys. ```APIDOC ## Client Key Options ### Description These keys are not strictly necessary for Parse Server but can be configured to restrict access to older clients. ### Parameters - **clientKey** (string) - Optional - The client key. - **javascriptKey** (string) - Optional - The JavaScript key. - **restAPIKey** (string) - Optional - The REST API key. - **dotNetKey** (string) - Optional - The .NET key. ``` -------------------------------- ### Build type definitions Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Manually trigger the generation of .d.ts files. ```bash npm run build:types ``` -------------------------------- ### Hash and Compare Passwords with Crypto Source: https://github.com/parse-community/parse-server/wiki/crypto.js Use these methods to securely hash plain-text passwords and verify them against stored hashes. Both methods return promises. ```javascript crypto.hash('hunter2').then( ... ).catch( ... ); crypto.compare('hunter2', 'previously-hashed-password-hash').then( ... ).catch( ... ); ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Sets the VERBOSE environment variable to log each request and response. ```bash VERBOSE='1' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY ``` -------------------------------- ### Configure GraphQL API and Custom Resolvers in Parse Server Source: https://context7.com/parse-community/parse-server/llms.txt Sets up a Parse Server instance with an integrated GraphQL server and demonstrates a custom Cloud Code resolver for complex queries. ```javascript // server setup with GraphQL const express = require('express'); const { ParseServer, ParseGraphQLServer } = require('parse-server'); const app = express(); const parseServer = new ParseServer({ databaseURI: 'mongodb://localhost:27017/myapp', appId: 'MY_APP_ID', masterKey: 'MY_MASTER_KEY', serverURL: 'http://localhost:1337/parse', publicServerURL: 'http://localhost:1337/parse' }); const parseGraphQLServer = new ParseGraphQLServer(parseServer, { graphQLPath: '/graphql', playgroundPath: '/playground' // Only for development }); await parseServer.start(); app.use('/parse', parseServer.app); parseGraphQLServer.applyGraphQL(app); app.listen(1337); // Custom GraphQL schema (schema.graphql) // extend type Query { // totalRevenue(startDate: Date!, endDate: Date!): Float! @resolve // } // Cloud function resolver (main.js) Parse.Cloud.define('totalRevenue', async (request) => { const { startDate, endDate } = request.params; const result = await new Parse.Query('Order') .greaterThanOrEqualTo('createdAt', new Date(startDate)) .lessThanOrEqualTo('createdAt', new Date(endDate)) .equalTo('status', 'completed') .aggregate([{ $group: { _id: null, total: { $sum: '$total' } } }]); return result[0]?.total || 0; }); ``` -------------------------------- ### Route Allow List Configuration Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Configure which API routes are accessible to external clients. ```APIDOC ## Route Allow List ### Description The `routeAllowList` option restricts which API routes are accessible to external clients. When set, all external requests are denied by default unless the route matches one of the configured regex patterns. Internal calls from Cloud Code, Cloud Jobs, and triggers are not affected. Master key and maintenance key requests bypass this restriction. ### Parameters - **routeAllowList** (array of strings) - Optional - An array of regex patterns to allow specific API routes. An empty array `[]` blocks all external non-master-key requests. ### Example ```js const server = ParseServer({ ...otherOptions, routeAllowList: [ 'classes/ChatMessage', 'classes/Public.*', 'users', 'login', 'functions/getMenu', 'health', ], }); ``` ### Note on Regex Matching Each entry is a regex pattern matched against the normalized route identifier. Patterns are auto-anchored with `^` and `$` for full-match semantics. For example, `classes/Chat` matches only `classes/Chat`, not `classes/ChatRoom`. Use `classes/Chat.*` to match both. ``` -------------------------------- ### Configuration API Source: https://github.com/parse-community/parse-server/blob/alpha/README.md Endpoints for retrieving server configuration information. ```APIDOC ## GET /config ### Description Retrieves the server configuration. ### Method GET ### Endpoint `/config` ### Response #### Success Response (200) - **config** (object) - An object containing server configuration settings. #### Response Example ```json { "config": { "appName": "My App", "masterKeyIps": [] } } ``` ``` ```APIDOC ## GET /graphql-config ### Description Retrieves the GraphQL configuration. ### Method GET ### Endpoint `/graphql-config` ### Response #### Success Response (200) - **config** (object) - An object containing GraphQL configuration settings. #### Response Example ```json { "config": { "enabled": true } } ``` ``` -------------------------------- ### Run local security vulnerability tests Source: https://github.com/parse-community/parse-server/blob/alpha/CONTRIBUTING.md Execute these commands locally to verify security fixes before publishing a public pull request. ```bash npm run test ``` ```bash npm run test:postgres:testonly ``` ```bash npm run madge:circular ``` ```bash npm run lint ``` ```bash npm run definitions ``` ```bash npm run build ```