@0x18b2ee/parse-server 中文文档教程
Parse Server 是一个开源后端,可以部署到任何可以运行 Node.js 的基础架构。
Our Sponsors
我们的支持者和赞助商帮助确保 Parse 平台的质量和及时开发。
Parse Server 与 Express 网络应用程序框架一起工作。 它可以添加到现有的 Web 应用程序中,也可以单独运行。
wiki 中提供了 Parse Server 的完整文档。 Parse Server 指南 是入门的好地方。 API 参考 和 Cloud 代码指南 也可用。 如果您有兴趣为 Parse Server 进行开发,开发指南 将帮助您做好准备向上。
- Getting Started
- Live Queries
- GraphQL (beta)
- Upgrading to 3.0.0
- Support
- Ride the Bleeding Edge
- Contributing
- Contributors
- Sponsors
- Backers
Getting Started
最快和最简单的入门方法是在本地运行 MongoDB 和 Parse Server。
Running Parse Server
在开始之前确保您已经安装:
- NodeJS that includes
npm
- MongoDB or PostgreSQL
- Optionally Docker
Locally
$ npm install -g parse-server mongodb-runner
$ mongodb-runner start
$ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://localhost/test
注意: 如果安装 -g
由于以下原因而失败权限问题(npm ERR!code 'EACCES'
),请参考此链接。
Inside a Docker container
$ git clone https://github.com/parse-community/parse-server
$ cd parse-server
$ docker build --tag parse-server .
$ docker run --name my-mongo -d mongo
$ docker run --name my-parse-server -p 1337:1337 --link my-mongo:mongo -d parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://mongo/test
您可以使用任意字符串作为您的应用程序 ID 和主密钥。 您的客户端将使用这些来向 Parse Server 进行身份验证。
就是这样! 您现在正在计算机上运行独立版本的 Parse Server。
使用远程 MongoDB? 在启动 parse-server
时传递 --databaseURI DATABASE_URI
参数。 在此处了解有关配置 Parse Server 的更多信息。 如需可用选项的完整列表,请运行 parse-server --help
。
Saving your first object
现在您正在运行 Parse Server,是时候保存您的第一个对象了。 我们将使用 REST API,但您可以使用任何 解析 SDK。 运行以下命令:
$ curl -X POST \
-H "X-Parse-Application-Id: APPLICATION_ID" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
http://localhost:1337/parse/classes/GameScore
您应该会得到类似这样的响应:
{
"objectId": "2ntvSpRGIK",
"createdAt": "2016-03-11T23:51:48.050Z"
}
您现在可以直接检索该对象(确保将 2ntvSpRGIK
替换为您在对象创建时收到的实际 objectId
created):
$ curl -X GET \
-H "X-Parse-Application-Id: APPLICATION_ID" \
http://localhost:1337/parse/classes/GameScore/2ntvSpRGIK
// Response
{
"objectId": "2ntvSpRGIK",
"score": 1337,
"playerName": "Sean Plott",
"cheatMode": false,
"updatedAt": "2016-03-11T23:51:48.050Z",
"createdAt": "2016-03-11T23:51:48.050Z"
}
但是,跟踪单个对象 ID 并不理想。 在大多数情况下,您将希望对集合运行查询,如下所示:
$ curl -X GET \
-H "X-Parse-Application-Id: APPLICATION_ID" \
http://localhost:1337/parse/classes/GameScore
// The response will provide all the matching objects within the `results` array:
{
"results": [
{
"objectId": "2ntvSpRGIK",
"score": 1337,
"playerName": "Sean Plott",
"cheatMode": false,
"updatedAt": "2016-03-11T23:51:48.050Z",
"createdAt": "2016-03-11T23:51:48.050Z"
}
]
}
要了解有关在 Parse Server 上使用保存和查询对象的更多信息,请查看 Parse文档。
Connect your app to Parse Server
Parse 为所有主要平台提供 SDK。 请参阅 Parse Server 指南以了解如何将您的应用连接到 Parse服务器。
Running Parse Server elsewhere
一旦您对项目的工作原理有了更好的了解,请参阅 Parse Server wiki 以了解 -将 Parse Server 部署到主要基础设施提供商的深度指南。 继续阅读以了解有关运行 Parse Server 的其他方法的更多信息。
Parse Server Sample Application
我们提供了一个基本的 Node.js 应用程序,它使用 Express 上的 Parse Server 模块并且可以轻松部署到各种基础设施提供商:
- Heroku and mLab
- AWS and Elastic Beanstalk
- Google App Engine
- Microsoft Azure
- SashiDo
- Digital Ocean
- Pivotal Web Services
- Back4app
- Glitch
- Flynn
Parse Server + Express
您还可以创建 Parse Server 的实例,并将其安装在新的或现有的 Express 网站上:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var api = new ParseServer({
databaseURI: 'mongodb://localhost:27017/dev', // Connection string for your MongoDB database
cloud: '/home/myApp/cloud/main.js', // Absolute 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
});
// Serve the Parse API on the /parse URL prefix
app.use('/parse', api);
app.listen(1337, function() {
console.log('parse-server-example running on port 1337.');
});
有关可用选项的完整列表,请运行 parse-server --help
或获取查看 解析服务器配置。
Configuration
可以使用以下选项配置 Parse Server。 您可以在运行独立的 parse-server
时将它们作为参数传递,或者使用 parse-server path/to/configuration.json
加载 JSON 格式的配置文件。 如果您在 Express 上使用 Parse Server,您还可以将这些作为选项传递给 ParseServer
对象。
有关可用选项的完整列表,请运行 parse-server --help
或查看 解析服务器配置。
Basic options
appId
(required) - The application id to host with this server instance. You can use any arbitrary string. For migrated apps, this should match your hosted Parse app.masterKey
(required) - The master key to use for overriding ACL security. You can use any arbitrary string. Keep it secret! For migrated apps, this should match your hosted Parse app.databaseURI
(required) - The connection string for your database, i.e.mongodb://user:pass@host.com/dbname
. Be sure to URL encode your password if your password has special characters.port
- The default port is 1337, specify this parameter to use a different port.serverURL
- URL to your Parse Server (don't forget to specify http:// or https://). This URL will be used when making requests to Parse Server from Cloud Code.cloud
- The absolute path to your cloud codemain.js
file.push
- Configuration options for APNS and GCM push. See the Push Notifications quick start.
Client key options
Parse Server 不再需要与 Parse 一起使用的客户端密钥。 如果您希望仍然需要它们,也许是为了能够拒绝访问旧客户端,您可以在初始化时设置密钥。 设置这些密钥中的任何一个都将要求所有请求提供配置的密钥之一。
clientKey
javascriptKey
restAPIKey
dotNetKey
Email verification and password reset
验证用户电子邮件地址和通过电子邮件启用密码重置需要电子邮件适配器。 作为 parse-server
包的一部分,我们提供了一个适配器,用于通过 Mailgun 发送电子邮件。 要使用它,请注册 Mailgun,并将其添加到您的初始化代码中:
var server = ParseServer({
...otherOptions,
// Enable email verification
verifyUserEmails: true,
// if `verifyUserEmails` is `true` and
// if `emailVerifyTokenValidityDuration` is `undefined` then
// email verify token never expires
// else
// email verify token expires after `emailVerifyTokenValidityDuration`
//
// `emailVerifyTokenValidityDuration` defaults to `undefined`
//
// email verify token below expires in 2 hours (= 2 * 60 * 60 == 7200 seconds)
emailVerifyTokenValidityDuration: 2 * 60 * 60, // in seconds (2 hours = 7200 seconds)
// set preventLoginWithUnverifiedEmail to false to allow user to login without verifying their email
// set preventLoginWithUnverifiedEmail to true to prevent user from login if their email is not verified
preventLoginWithUnverifiedEmail: false, // defaults to false
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'https://example.com/parse',
// Your apps name. This will appear in the subject and body of the emails that are sent.
appName: 'Parse App',
// The email adapter
emailAdapter: {
module: '@parse/simple-mailgun-adapter',
options: {
// The address that your emails come from
fromAddress: 'parse@example.com',
// Your domain from mailgun.com
domain: 'example.com',
// Your API key from mailgun.com
apiKey: 'key-mykey',
}
},
// account lockout policy setting (OPTIONAL) - defaults to undefined
// if the account lockout policy is set and there are more than `threshold` number of failed login attempts then the `login` api call returns error code `Parse.Error.OBJECT_NOT_FOUND` with error message `Your account is locked due to multiple failed login attempts. Please try again after <duration> minute(s)`. After `duration` minutes of no login attempts, the application will allow the user to try login again.
accountLockout: {
duration: 5, // duration policy setting determines the number of minutes that a locked-out account remains locked out before automatically becoming unlocked. Set it to a value greater than 0 and less than 100000.
threshold: 3, // threshold policy setting determines the number of failed sign-in attempts that will cause a user account to be locked. Set it to an integer value greater than 0 and less than 1000.
},
// optional settings to enforce password policies
passwordPolicy: {
// Two optional settings to enforce strong passwords. Either one or both can be specified.
// If both are specified, both checks must pass to accept the password
// 1. a RegExp object or a regex string representing the pattern to enforce
validatorPattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/, // enforce password with at least 8 char with at least 1 lower case, 1 upper case and 1 digit
// 2. a callback function to be invoked to validate the password
validatorCallback: (password) => { return validatePassword(password) },
validationError: 'Password must contain at least 1 digit.' // optional error message to be sent instead of the default "Password does not meet the Password Policy requirements." message.
doNotAllowUsername: true, // optional setting to disallow username in passwords
maxPasswordAge: 90, // optional setting in days for password expiry. Login fails if user does not reset the password within this period after signup/last reset.
maxPasswordHistory: 5, // optional setting to prevent reuse of previous n passwords. Maximum value that can be specified is 20. Not specifying it or specifying 0 will not enforce history.
//optional setting to set a validity duration for password reset links (in seconds)
resetTokenValidityDuration: 24*60*60, // expire after 24 hours
}
});
您还可以使用社区提供的其他电子邮件适配器,例如:
- parse-smtp-template (Multi Language and Multi Template)
- parse-server-postmark-adapter
- parse-server-sendgrid-adapter
- parse-server-mandrill-adapter
- parse-server-simple-ses-adapter
- parse-server-mailgun-adapter-template
- parse-server-sendinblue-adapter
- parse-server-mailjet-adapter
- simple-parse-smtp-adapter
- parse-server-generic-email-adapter
Custom Pages
可以更改应用程序的默认页面并将用户重定向到另一个路径或域.
var server = ParseServer({
...otherOptions,
customPages {
passwordResetSuccess: "http://yourapp.com/passwordResetSuccess",
verifyEmailSuccess: "http://yourapp.com/verifyEmailSuccess",
parseFrameURL: "http://yourapp.com/parseFrameURL",
linkSendSuccess: "http://yourapp.com/linkSendSuccess",
linkSendFail: "http://yourapp.com/linkSendFail",
invalidLink: "http://yourapp.com/invalidLink",
invalidVerificationLink: "http://yourapp.com/invalidVerificationLink",
choosePassword: "http://yourapp.com/choosePassword"
}
})
Using environment variables to configure Parse Server
您可以使用环境变量配置 Parse Server:
PORT
PARSE_SERVER_APPLICATION_ID
PARSE_SERVER_MASTER_KEY
PARSE_SERVER_DATABASE_URI
PARSE_SERVER_URL
PARSE_SERVER_CLOUD
默认端口为 1337,要使用不同的端口,请设置 PORT 环境变量:
$ PORT=8080 parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
有关可配置环境变量的完整列表,请运行 parse-server --help
或查看 解析服务器配置。
Available Adapters
所有官方适配器都作为作用域包在 npm (@parse) 上分发。
Parse Server Modules 组织也提供了一些维护良好的适配器。
您还可以通过搜索 npm。
Configuring File Adapters
Parse Server 允许开发人员在托管文件时从多个选项中进行选择:
GridFSBucketAdapter
, which is backed by MongoDB;S3Adapter
, which is backed by Amazon S3; orGCSAdapter
, which is backed by Google Cloud Storage
默认情况下使用 GridFSBucketAdapter
并且不需要设置,但如果您对使用 S3 或 Google Cloud Storage 感兴趣,可以在解析服务器指南。
Logging
默认情况下,Parse Server 将记录:
- to the console
- daily rotating files as new line delimited JSON
日志也可以在 Parse Dashboard 中查看。
想要记录每个请求和响应?在启动parse-server
时设置VERBOSE
环境变量。 用法:- VERBOSE='1' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
想要将日志放在不同的文件夹中?传递 PARSE_SERVER_LOGS_FOLDER
启动 parse-server
时的环境变量。 用法:- PARSE_SERVER_LOGS_FOLDER='
要记录特定级别? 启动时传递 logLevel
参数 parse-server
。 用法:- parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --logLevel LOG_LEVEL
想要换行分隔的 JSON 错误日志(供 CloudWatch、Google Cloud Logging 等使用)? 在启动 parse-server
时传递 JSON_LOGS
环境变量。 用法:- JSON_LOGS='1' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
Live Queries
实时查询旨在用于实时反应应用程序,仅使用传统查询范式可能会导致多个问题,例如响应时间增加以及网络和服务器使用率高。 在需要使用来自数据库的新数据不断更新页面的情况下,应使用实时查询,这通常发生在(但不限于)在线游戏、消息客户端和共享待办事项列表中。
查看实时查询指南,实时查询服务器设置指南 和 实时查询协议规范。 您可以设置独立服务器或多个实例以实现可伸缩性(推荐)。
GraphQL (beta)
GraphQL 由 Facebook 开发,是一种用于 API 的开源数据查询和操作语言。 除了传统的 REST API 之外,Parse Server 还会根据您当前的应用程序模式自动生成 GraphQL API。 Parse Server 还允许您定义自定义 GraphQL 查询和突变,其解析器可以绑定到您的云代码函数。
⚠️ Parse GraphQL beta
实现功能齐全,但正在讨论如何改进它。 因此,新版本的 Parse Server 可以为当前的 API 带来突破性的变化。
Running
Using the CLI
运行 Parse GraphQL API 的最简单方法是通过 CLI:
$ 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
启动服务器后,您可以在浏览器中访问 http://localhost:1337/playground 以开始使用您的 GraphQL API。
注意:在生产中不要使用 --mountPlayground 选项。 Parse Dashboard 有一个内置的 GraphQL Playground,它是生产应用程序的推荐选项。
Using Docker
您还可以在 Docker 容器内运行 Parse GraphQL API:
$ git clone https://github.com/parse-community/parse-server
$ cd parse-server
$ docker build --tag parse-server .
$ docker run --name my-mongo -d mongo
$ docker run --name my-parse-server --link my-mongo:mongo -p 1337:1337 -d parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://mongo/test --publicServerURL http://localhost:1337/parse --mountGraphQL --mountPlayground
启动服务器后,您可以在浏览器中访问 http://localhost:1337/playground 以开始使用您的 GraphQL API。
注意:在生产中不要使用 --mountPlayground 选项。 Parse Dashboard 有一个内置的 GraphQL Playground,它是生产应用程序的推荐选项。
Using Express.js
您还可以将 GraphQL API 与 REST API 一起或单独安装在 Express.js 应用程序中。 您首先需要创建一个新项目并安装所需的依赖项:
$ mkdir my-app
$ cd my-app
$ npm install parse-server express --save
然后,创建一个包含以下内容的 index.js
文件:
const express = require('express');
const { default: 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
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');
});
最后启动您的应用程序:
$ npx mongodb-runner start
$ node index.js
启动应用程序后,您可以访问 http: //localhost:1337/playground 在您的浏览器中开始使用您的 GraphQL API。
注意:不要在生产环境中安装 GraphQL Playground。 Parse Dashboard 有一个内置的 GraphQL Playground,它是生产应用程序的推荐选项。
Checking the API health
运行以下命令:
query Health {
health
}
您应该收到以下响应:
{
"data": {
"health": true
}
}
Creating your first class
由于您的应用程序还没有任何模式,您可以使用 createClass
突变来创建您的第一个类。 运行以下命令:
mutation CreateClass {
createClass(
name: "GameScore"
schemaFields: {
addStrings: [{ name: "playerName" }]
addNumbers: [{ name: "score" }]
addBooleans: [{ name: "cheatMode" }]
}
) {
name
schemaFields {
name
__typename
}
}
}
您应该收到以下响应:
{
"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"
}
]
}
}
}
Using automatically generated operations
Parse Server 从您创建的第一个类中学习,现在您的模式中有 GameScore
类。 您现在可以开始使用自动生成的操作了!
运行以下命令创建您的第一个对象:
mutation CreateGameScore {
createGameScore(
fields: {
playerName: "Sean Plott"
score: 1337
cheatMode: false
}
) {
id
updatedAt
createdAt
playerName
score
cheatMode
ACL
}
}
您应该会收到类似这样的响应:
{
"data": {
"createGameScore": {
"id": "XN75D94OBD",
"updatedAt": "2019-09-17T06:50:26.357Z",
"createdAt": "2019-09-17T06:50:26.357Z",
"playerName": "Sean Plott",
"score": 1337,
"cheatMode": false,
"ACL": null
}
}
}
您还可以对这个新类运行查询:
query GameScores {
gameScores {
results {
id
updatedAt
createdAt
playerName
score
cheatMode
ACL
}
}
}
您应该会收到类似这样的响应:
{
"data": {
"gameScores": {
"results": [
{
"id": "XN75D94OBD",
"updatedAt": "2019-09-17T06:50:26.357Z",
"createdAt": "2019-09-17T06:50:26.357Z",
"playerName": "Sean Plott",
"score": 1337,
"cheatMode": false,
"ACL": null
}
]
}
}
}
Customizing your GraphQL Schema
Parse GraphQL Server allows you to create a custom GraphQL schema with自己的查询和突变与自动生成的查询和突变合并。 您可以使用常规云代码函数解决这些操作。
要开始创建您的自定义模式,您需要编写一个 schema.graphql
文件并使用 --graphQLSchema
和 --cloud
选项初始化 Parse Server :
$ 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
Creating your first custom query
将下面的代码用于您的 schema.graphql
和 main.js
文件。 然后重新启动您的解析服务器。
# schema.graphql
extend type Query {
hello: String! @resolve
}
// main.js
Parse.Cloud.define('hello', async () => {
return 'Hello world!';
});
您现在可以使用 GraphQL Playground 运行您的自定义查询:
query {
hello
}
您应该收到以下响应:
{
"data": {
"hello": "Hello world!"
}
}
Learning more
Parse GraphQL Guide 是一个非常学习如何使用 Parse GraphQL API 的好资源。
您的 GraphQL Playground 中还有一个非常强大的工具。 请查看 GraphQL Playground 的右侧。 您将看到 DOCS
和 SCHEMA
菜单。 它们是通过分析您的应用程序模式自动生成的。 请参考它们并详细了解您可以使用 Parse GraphQL API 执行的所有操作。
此外,GraphQL 学习部分 是了解更多有关 GraphQL 语言的强大功能的非常好的来源。
Upgrading to 3.0.0
从 3.0.0 开始,parse-server 使用 JS SDK 2.0 版。 简而言之,parse SDK v2.0 移除了主干样式回调以及 Parse.Promise 对象以支持原生承诺。 所有 Cloud Code 接口也已更新以反映这些更改,并且所有骨干样式响应对象都被删除并替换为 Promise 样式解析。
我们编写了一份迁移指南,希望这能帮助您过渡到下一个主要版本。
Support
请查看我们的支持文档。
如果您认为您发现了 Parse Server 的问题,请确保在报告问题:
Want to ride the bleeding edge?
出于多种原因,建议使用部署 npm 的构建,但是如果您想使用 最新的尚未发布的解析服务器版本,你可以通过依赖 直接在这个分支上:
npm install parse-community/parse-server.git#master
Experimenting
你也可以使用你自己的分支,并通过指定它们进行工作分支:
npm install github:myUsername/parse-server#my-awesome-feature
不要忘记,如果你打算远程部署它,你应该运行 npm install
--保存
选项。
Contributing
我们真的希望 Parse 成为你的,看到它在开源社区中成长壮大。 请参阅Contributing to Parse Server guide。
Contributors
这个项目的存在要归功于所有做出贡献的人……我们很乐意看到你出现在这个名单上!
Sponsors
通过成为赞助商来支持这个项目。 您的徽标将显示在此处,并带有指向您网站的链接。 成为赞助商!
Backers
每月捐款支持我们,帮助我们继续开展活动。 成为支持者!
自 2017 年 4 月 5 日起,Parse, LLC 已将此代码转移到 parse -社区组织,将不再贡献或分发此代码。
Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js.
Our Sponsors
Our backers and sponsors help to ensure the quality and timely development of the Parse Platform.
Parse Server works with the Express web application framework. It can be added to existing web applications, or run by itself.
The full documentation for Parse Server is available in the wiki. The Parse Server guide is a good place to get started. An API reference and Cloud Code guide are also available. If you're interested in developing for Parse Server, the Development guide will help you get set up.
- Getting Started
- Live Queries
- GraphQL (beta)
- Upgrading to 3.0.0
- Support
- Ride the Bleeding Edge
- Contributing
- Contributors
- Sponsors
- Backers
Getting Started
The fastest and easiest way to get started is to run MongoDB and Parse Server locally.
Running Parse Server
Before you start make sure you have installed:
- NodeJS that includes
npm
- MongoDB or PostgreSQL
- Optionally Docker
Locally
$ npm install -g parse-server mongodb-runner
$ mongodb-runner start
$ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://localhost/test
Note: If installation with -g
fails due to permission problems (npm ERR! code 'EACCES'
), please refer to this link.
Inside a Docker container
$ git clone https://github.com/parse-community/parse-server
$ cd parse-server
$ docker build --tag parse-server .
$ docker run --name my-mongo -d mongo
$ docker run --name my-parse-server -p 1337:1337 --link my-mongo:mongo -d parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://mongo/test
You can use any arbitrary string as your application id and master key. These will be used by your clients to authenticate with the Parse Server.
That's it! You are now running a standalone version of Parse Server on your machine.
Using a remote MongoDB? Pass the --databaseURI DATABASE_URI
parameter when starting parse-server
. Learn more about configuring Parse Server here. For a full list of available options, run parse-server --help
.
Saving your first object
Now that you're running Parse Server, it is time to save your first object. We'll use the REST API, but you can easily do the same using any of the Parse SDKs. Run the following:
$ curl -X POST \
-H "X-Parse-Application-Id: APPLICATION_ID" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
http://localhost:1337/parse/classes/GameScore
You should get a response similar to this:
{
"objectId": "2ntvSpRGIK",
"createdAt": "2016-03-11T23:51:48.050Z"
}
You can now retrieve this object directly (make sure to replace 2ntvSpRGIK
with the actual objectId
you received when the object was created):
$ curl -X GET \
-H "X-Parse-Application-Id: APPLICATION_ID" \
http://localhost:1337/parse/classes/GameScore/2ntvSpRGIK
// Response
{
"objectId": "2ntvSpRGIK",
"score": 1337,
"playerName": "Sean Plott",
"cheatMode": false,
"updatedAt": "2016-03-11T23:51:48.050Z",
"createdAt": "2016-03-11T23:51:48.050Z"
}
Keeping tracks of individual object ids is not ideal, however. In most cases you will want to run a query over the collection, like so:
$ curl -X GET \
-H "X-Parse-Application-Id: APPLICATION_ID" \
http://localhost:1337/parse/classes/GameScore
// The response will provide all the matching objects within the `results` array:
{
"results": [
{
"objectId": "2ntvSpRGIK",
"score": 1337,
"playerName": "Sean Plott",
"cheatMode": false,
"updatedAt": "2016-03-11T23:51:48.050Z",
"createdAt": "2016-03-11T23:51:48.050Z"
}
]
}
To learn more about using saving and querying objects on Parse Server, check out the Parse documentation.
Connect your app to Parse Server
Parse provides SDKs for all the major platforms. Refer to the Parse Server guide to learn how to connect your app to Parse Server.
Running Parse Server elsewhere
Once you have a better understanding of how the project works, please refer to the Parse Server wiki for in-depth guides to deploy Parse Server to major infrastructure providers. Read on to learn more about additional ways of running Parse Server.
Parse Server Sample Application
We have provided a basic Node.js application that uses the Parse Server module on Express and can be easily deployed to various infrastructure providers:
- Heroku and mLab
- AWS and Elastic Beanstalk
- Google App Engine
- Microsoft Azure
- SashiDo
- Digital Ocean
- Pivotal Web Services
- Back4app
- Glitch
- Flynn
Parse Server + Express
You can also create an instance of Parse Server, and mount it on a new or existing Express website:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var app = express();
var api = new ParseServer({
databaseURI: 'mongodb://localhost:27017/dev', // Connection string for your MongoDB database
cloud: '/home/myApp/cloud/main.js', // Absolute 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
});
// Serve the Parse API on the /parse URL prefix
app.use('/parse', api);
app.listen(1337, function() {
console.log('parse-server-example running on port 1337.');
});
For a full list of available options, run parse-server --help
or take a look at Parse Server Configurations.
Configuration
Parse Server can be configured using the following options. You may pass these as parameters when running a standalone parse-server
, or by loading a configuration file in JSON format using parse-server path/to/configuration.json
. If you're using Parse Server on Express, you may also pass these to the ParseServer
object as options.
For the full list of available options, run parse-server --help
or take a look at Parse Server Configurations.
Basic options
appId
(required) - The application id to host with this server instance. You can use any arbitrary string. For migrated apps, this should match your hosted Parse app.masterKey
(required) - The master key to use for overriding ACL security. You can use any arbitrary string. Keep it secret! For migrated apps, this should match your hosted Parse app.databaseURI
(required) - The connection string for your database, i.e.mongodb://user:pass@host.com/dbname
. Be sure to URL encode your password if your password has special characters.port
- The default port is 1337, specify this parameter to use a different port.serverURL
- URL to your Parse Server (don't forget to specify http:// or https://). This URL will be used when making requests to Parse Server from Cloud Code.cloud
- The absolute path to your cloud codemain.js
file.push
- Configuration options for APNS and GCM push. See the Push Notifications quick start.
Client key options
The client keys used with Parse are no longer necessary with Parse Server. If you wish to still require them, perhaps to be able to refuse access to older clients, you can set the keys at initialization time. Setting any of these keys will require all requests to provide one of the configured keys.
clientKey
javascriptKey
restAPIKey
dotNetKey
Email verification and password reset
Verifying user email addresses and enabling password reset via email requires an email adapter. As part of the parse-server
package we provide an adapter for sending email through Mailgun. To use it, sign up for Mailgun, and add this to your initialization code:
var server = ParseServer({
...otherOptions,
// Enable email verification
verifyUserEmails: true,
// if `verifyUserEmails` is `true` and
// if `emailVerifyTokenValidityDuration` is `undefined` then
// email verify token never expires
// else
// email verify token expires after `emailVerifyTokenValidityDuration`
//
// `emailVerifyTokenValidityDuration` defaults to `undefined`
//
// email verify token below expires in 2 hours (= 2 * 60 * 60 == 7200 seconds)
emailVerifyTokenValidityDuration: 2 * 60 * 60, // in seconds (2 hours = 7200 seconds)
// set preventLoginWithUnverifiedEmail to false to allow user to login without verifying their email
// set preventLoginWithUnverifiedEmail to true to prevent user from login if their email is not verified
preventLoginWithUnverifiedEmail: false, // defaults to false
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'https://example.com/parse',
// Your apps name. This will appear in the subject and body of the emails that are sent.
appName: 'Parse App',
// The email adapter
emailAdapter: {
module: '@parse/simple-mailgun-adapter',
options: {
// The address that your emails come from
fromAddress: 'parse@example.com',
// Your domain from mailgun.com
domain: 'example.com',
// Your API key from mailgun.com
apiKey: 'key-mykey',
}
},
// account lockout policy setting (OPTIONAL) - defaults to undefined
// if the account lockout policy is set and there are more than `threshold` number of failed login attempts then the `login` api call returns error code `Parse.Error.OBJECT_NOT_FOUND` with error message `Your account is locked due to multiple failed login attempts. Please try again after <duration> minute(s)`. After `duration` minutes of no login attempts, the application will allow the user to try login again.
accountLockout: {
duration: 5, // duration policy setting determines the number of minutes that a locked-out account remains locked out before automatically becoming unlocked. Set it to a value greater than 0 and less than 100000.
threshold: 3, // threshold policy setting determines the number of failed sign-in attempts that will cause a user account to be locked. Set it to an integer value greater than 0 and less than 1000.
},
// optional settings to enforce password policies
passwordPolicy: {
// Two optional settings to enforce strong passwords. Either one or both can be specified.
// If both are specified, both checks must pass to accept the password
// 1. a RegExp object or a regex string representing the pattern to enforce
validatorPattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/, // enforce password with at least 8 char with at least 1 lower case, 1 upper case and 1 digit
// 2. a callback function to be invoked to validate the password
validatorCallback: (password) => { return validatePassword(password) },
validationError: 'Password must contain at least 1 digit.' // optional error message to be sent instead of the default "Password does not meet the Password Policy requirements." message.
doNotAllowUsername: true, // optional setting to disallow username in passwords
maxPasswordAge: 90, // optional setting in days for password expiry. Login fails if user does not reset the password within this period after signup/last reset.
maxPasswordHistory: 5, // optional setting to prevent reuse of previous n passwords. Maximum value that can be specified is 20. Not specifying it or specifying 0 will not enforce history.
//optional setting to set a validity duration for password reset links (in seconds)
resetTokenValidityDuration: 24*60*60, // expire after 24 hours
}
});
You can also use other email adapters contributed by the community such as:
- parse-smtp-template (Multi Language and Multi Template)
- parse-server-postmark-adapter
- parse-server-sendgrid-adapter
- parse-server-mandrill-adapter
- parse-server-simple-ses-adapter
- parse-server-mailgun-adapter-template
- parse-server-sendinblue-adapter
- parse-server-mailjet-adapter
- simple-parse-smtp-adapter
- parse-server-generic-email-adapter
Custom Pages
It’s possible to change the default pages of the app and redirect the user to another path or domain.
var server = ParseServer({
...otherOptions,
customPages {
passwordResetSuccess: "http://yourapp.com/passwordResetSuccess",
verifyEmailSuccess: "http://yourapp.com/verifyEmailSuccess",
parseFrameURL: "http://yourapp.com/parseFrameURL",
linkSendSuccess: "http://yourapp.com/linkSendSuccess",
linkSendFail: "http://yourapp.com/linkSendFail",
invalidLink: "http://yourapp.com/invalidLink",
invalidVerificationLink: "http://yourapp.com/invalidVerificationLink",
choosePassword: "http://yourapp.com/choosePassword"
}
})
Using environment variables to configure Parse Server
You may configure the Parse Server using environment variables:
PORT
PARSE_SERVER_APPLICATION_ID
PARSE_SERVER_MASTER_KEY
PARSE_SERVER_DATABASE_URI
PARSE_SERVER_URL
PARSE_SERVER_CLOUD
The default port is 1337, to use a different port set the PORT environment variable:
$ PORT=8080 parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
For the full list of configurable environment variables, run parse-server --help
or take a look at Parse Server Configuration.
Available Adapters
All official adapters are distributed as scoped pacakges on npm (@parse).
Some well maintained adapters are also available on the Parse Server Modules organization.
You can also find more adapters maintained by the community by searching on npm.
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; orGCSAdapter
, which is backed by Google Cloud Storage
GridFSBucketAdapter
is used by default and requires no setup, but if you're interested in using S3 or Google Cloud Storage, additional configuration information is available in the Parse Server guide.
Logging
Parse Server will, by default, log:
- to the console
- daily rotating files as new line delimited JSON
Logs are also viewable in Parse Dashboard.
Want to log each request and response? Set the VERBOSE
environment variable when starting parse-server
. Usage :- VERBOSE='1' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
Want logs to be in placed in a different folder? Pass the PARSE_SERVER_LOGS_FOLDER
environment variable when starting parse-server
. Usage :- PARSE_SERVER_LOGS_FOLDER='<path-to-logs-folder>' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
Want to log specific levels? Pass the logLevel
parameter when starting parse-server
. Usage :- parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --logLevel LOG_LEVEL
Want new line delimited JSON error logs (for consumption by CloudWatch, Google Cloud Logging, etc)? Pass the JSON_LOGS
environment variable when starting parse-server
. Usage :- JSON_LOGS='1' parse-server --appId APPLICATION_ID --masterKey MASTER_KEY
Live Queries
Live queries are meant to be used in real-time reactive applications, where just using the traditional query paradigm could cause several problems, like increased response time and high network and server usage. Live queries should be used in cases where you need to continuously update a page with fresh data coming from the database, which often happens in (but is not limited to) online games, messaging clients and shared to-do lists.
Take a look at Live Query Guide, Live Query Server Setup Guide and Live Query Protocol Specification. You can setup a standalone server or multiple instances for scalability (recommended).
GraphQL (beta)
GraphQL, developed by Facebook, is an open-source data query and manipulation language for APIs. In addition to the traditional REST API, Parse Server automatically generates a GraphQL API based on your current application schema. Parse Server also allows you to define your custom GraphQL queries and mutations, whose resolvers can be bound to your cloud code functions.
⚠️ The Parse GraphQL beta
implementation is fully functional but discussions are taking place on how to improve it. So new versions of Parse Server can bring breaking changes to the current API.
Running
Using the CLI
The easiest way to run the Parse GraphQL API is through the CLI:
$ 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
After starting the server, you can visit http://localhost:1337/playground in your browser to start playing with your GraphQL API.
Note: Do NOT use --mountPlayground option in production. Parse Dashboard has a built-in GraphQL Playground and it is the recommended option for production apps.
Using Docker
You can also run the Parse GraphQL API inside a Docker container:
$ git clone https://github.com/parse-community/parse-server
$ cd parse-server
$ docker build --tag parse-server .
$ docker run --name my-mongo -d mongo
$ docker run --name my-parse-server --link my-mongo:mongo -p 1337:1337 -d parse-server --appId APPLICATION_ID --masterKey MASTER_KEY --databaseURI mongodb://mongo/test --publicServerURL http://localhost:1337/parse --mountGraphQL --mountPlayground
After starting the server, you can visit http://localhost:1337/playground in your browser to start playing with your GraphQL API.
Note: Do NOT use --mountPlayground option in production. Parse Dashboard has a built-in GraphQL Playground and it is the recommended option for production apps.
Using Express.js
You can also mount the GraphQL API in an Express.js application together with the REST API or solo. You first need to create a new project and install the required dependencies:
$ mkdir my-app
$ cd my-app
$ npm install parse-server express --save
Then, create an index.js
file with the following content:
const express = require('express');
const { default: 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
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');
});
And finally start your app:
$ npx mongodb-runner start
$ node index.js
After starting the app, you can visit http://localhost:1337/playground in your browser to start playing with your GraphQL API.
Note: Do NOT mount the GraphQL Playground in production. Parse Dashboard has a built-in GraphQL Playground and it is the recommended option for production apps.
Checking the API health
Run the following:
query Health {
health
}
You should receive the following response:
{
"data": {
"health": true
}
}
Creating your first class
Since your application does not have any schema yet, you can use the createClass
mutation to create your first class. Run the following:
mutation CreateClass {
createClass(
name: "GameScore"
schemaFields: {
addStrings: [{ name: "playerName" }]
addNumbers: [{ name: "score" }]
addBooleans: [{ name: "cheatMode" }]
}
) {
name
schemaFields {
name
__typename
}
}
}
You should receive the following response:
{
"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"
}
]
}
}
}
Using automatically generated operations
Parse Server learned from the first class that you created and now you have the GameScore
class in your schema. You can now start using the automatically generated operations!
Run the following to create your first object:
mutation CreateGameScore {
createGameScore(
fields: {
playerName: "Sean Plott"
score: 1337
cheatMode: false
}
) {
id
updatedAt
createdAt
playerName
score
cheatMode
ACL
}
}
You should receive a response similar to this:
{
"data": {
"createGameScore": {
"id": "XN75D94OBD",
"updatedAt": "2019-09-17T06:50:26.357Z",
"createdAt": "2019-09-17T06:50:26.357Z",
"playerName": "Sean Plott",
"score": 1337,
"cheatMode": false,
"ACL": null
}
}
}
You can also run a query to this new class:
query GameScores {
gameScores {
results {
id
updatedAt
createdAt
playerName
score
cheatMode
ACL
}
}
}
You should receive a response similar to this:
{
"data": {
"gameScores": {
"results": [
{
"id": "XN75D94OBD",
"updatedAt": "2019-09-17T06:50:26.357Z",
"createdAt": "2019-09-17T06:50:26.357Z",
"playerName": "Sean Plott",
"score": 1337,
"cheatMode": false,
"ACL": null
}
]
}
}
}
Customizing your GraphQL Schema
Parse GraphQL Server allows you to create a custom GraphQL schema with own queries and mutations to be merged with the auto-generated ones. You can resolve these operations using your regular cloud code functions.
To start creating your custom schema, you need to code a schema.graphql
file and initialize Parse Server with --graphQLSchema
and --cloud
options:
$ 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
Creating your first custom query
Use the code below for your schema.graphql
and main.js
files. Then restart your Parse Server.
# schema.graphql
extend type Query {
hello: String! @resolve
}
// main.js
Parse.Cloud.define('hello', async () => {
return 'Hello world!';
});
You can now run your custom query using GraphQL Playground:
query {
hello
}
You should receive the response below:
{
"data": {
"hello": "Hello world!"
}
}
Learning more
The Parse GraphQL Guide is a very good source for learning how to use the Parse GraphQL API.
You also have a very powerful tool inside your GraphQL Playground. Please look at the right side of your GraphQL Playground. You will see the DOCS
and SCHEMA
menus. They are automatically generated by analyzing your application schema. Please refer to them and learn more about everything that you can do with your Parse GraphQL API.
Additionally, the GraphQL Learn Section is a very good source to learn more about the power of the GraphQL language.
Upgrading to 3.0.0
Starting 3.0.0, parse-server uses the JS SDK version 2.0. In short, parse SDK v2.0 removes the backbone style callbacks as well as the Parse.Promise object in favor of native promises. All the Cloud Code interfaces also have been updated to reflect those changes, and all backbone style response objects are removed and replaced by Promise style resolution.
We have written up a migration guide, hoping this will help you transition to the next major release.
Support
Please take a look at our support document.
If you believe you've found an issue with Parse Server, make sure these boxes are checked before reporting an issue:
[ ] You've met the prerequisites.
[ ] You're running the latest version of Parse Server.
[ ] You've searched through existing issues. Chances are that your issue has been reported or resolved before.
Want to ride the bleeding edge?
It is recommend to use builds deployed npm for many reasons, but if you want to use the latest not-yet-released version of parse-server, you can do so by depending directly on this branch:
npm install parse-community/parse-server.git#master
Experimenting
You can also use your own forks, and work in progress branches by specifying them:
npm install github:myUsername/parse-server#my-awesome-feature
And don't forget, if you plan to deploy it remotely, you should run npm install
with the --save
option.
Contributing
We really want Parse to be yours, to see it grow and thrive in the open source community. Please see the Contributing to Parse Server guide.
Contributors
This project exists thanks to all the people who contribute… we'd love to see your face on this list!
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Become a sponsor!
Backers
Support us with a monthly donation and help us continue our activities. Become a backer!
As of April 5, 2017, Parse, LLC has transferred this code to the parse-community organization, and will no longer be contributing to or distributing this code.