How to call cloud function from Parse via GraphQL - docker-compose

I have the following docker-compose:
version: '3.9'
services:
database:
image: mongo:6.0.2
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
volumes:
- ${HOME}/_DOCKER_DATA_/database:/data/db
server:
restart: always
image: parseplatform/parse-server:5.3.0
ports:
- 1337:1337
environment:
- PARSE_SERVER_APPLICATION_ID=APP_ID
- PARSE_SERVER_APPLICATION_NAME=COOK_NAME
- PARSE_SERVER_MASTER_KEY=MASTER_KEY
- PARSE_SERVER_DATABASE_URI=mongodb://admin:admin#mongo/parse_server?authSource=admin
- PARSE_SERVER_URL=http://10.0.2.2:1337/parse
- PARSE_SERVER_MOUNT_GRAPHQL=true
- PARSE_SERVER_CLOUD=/parse-server/cloud/main.js
links:
- database:mongo
volumes:
- ${HOME}/_DOCKER_DATA_/server:/data/server
- ../cloud:/parse-server/cloud
dashboard:
image: parseplatform/parse-dashboard:5.0.0
ports:
- "4040:4040"
depends_on:
- server
environment:
- PARSE_DASHBOARD_APP_ID=COOK_APP
- PARSE_DASHBOARD_MASTER_KEY=MASTER_KEY_1
- PARSE_DASHBOARD_USER_ID=admin
- PARSE_DASHBOARD_USER_PASSWORD=admin
- PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=true
- PARSE_DASHBOARD_SERVER_URL=http://localhost:1337/parse
- PARSE_DASHBOARD_GRAPHQL_SERVER_URL=http://localhost:1337/graphql
volumes:
- ${HOME}/_DOCKER_DATA_/dashboard:/data/dashboard
And also the fallowing .graphqlconfig in the root of my project:
{
"name": "Untitled GraphQL Schema",
"schemaPath": "schema.graphql",
"extensions": {
"endpoints": {
"Default GraphQL Endpoint": {
"url": "http://localhost:1337/graphql",
"headers": {
"X-Parse-Application-Id": "APP_ID",
"X-Parse-Master-Key": "MASTER_KEY"
},
"introspect": true
}
}
}
}
inside of my root project I have a folder called "cloud" which has inside a main.js and also a schema.graphql.
Main.js:
Parse.Cloud.define("checkGraphQLSupport", async req => {
if (parseGraphQLServer){
return "This App has GraphQL support.";
} else {
return "This App does not have GraphQL support. Wrong Parse version maybe?";
}
});
schema.graphql
extend type Query {
checkGraphQLSupport: String! #resolve(to: "checkGraphQLSupport")
}
I am trying to call from http://0.0.0.0:4040/apps/COOK_APP/api_console/graphql the cloud function via graphql by using the following query:
query {
checkGraphQLSupport
}
But this is not working and I get the fallowing error message:
"Cannot query field "checkGraphQLSupport" on type "Query"."
Can anyone explain to me what I am doing wrong? All what I am trying to do is to call the cloud code using graphql.

Try to add the env var PARSE_SERVER_GRAPH_QLSCHEMA=/parse-server/cloud/schema.graphql

Related

Flutter can not connect to the docker localhost parse-server

I am trying to run a parse-server and parse-dashboard via the following docker-compose.yml
docker-compose:
version: '3.9'
services:
database:
image: mongo:5.0
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: admin
volumes:
- data_volume:/data/mongodb
server:
restart: always
image: parseplatform/parse-server:4.10.4
ports:
- 1337:1337
environment:
- PARSE_SERVER_APPLICATION_ID=COOK_APP
- PARSE_SERVER_MASTER_KEY=MASTER_KEY_1
- PARSE_SERVER_CLIENT_KEY=CLIENT_KEY_1
- PARSE_SERVER_DATABASE_URI=mongodb://admin:admin#mongo/parse_server?authSource=admin
- PARSE_ENABLE_CLOUD_CODE=yes
links:
- database:mongo
volumes:
- data_volume:/data/server
- ./../lib/core/database/parse_server/cloud:/parse-server/cloud
dashboard:
image: parseplatform/parse-dashboard:4.0.0
ports:
- "4040:4040"
depends_on:
- server
restart: always
environment:
- PARSE_DASHBOARD_APP_ID=COOK_APP
- PARSE_DASHBOARD_MASTER_KEY=MASTER_KEY_1
- PARSE_DASHBOARD_USER_ID=admin
- PARSE_DASHBOARD_USER_PASSWORD=admin
- PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=true
- PARSE_DASHBOARD_SERVER_URL=http://localhost:1337/parse
volumes:
- data_volume:/data/dashboard
volumes:
data_volume:
driver: local
After the container is running via docker-compose up I am trying to connect to it using Flutter and write a new class to my server:
Flutter code:
import 'package:flutter/material.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
const keyApplicationId = 'COOK_APP';
const keyClientKey = 'CLIENT_KEY_1';
const keyParseServerUrl = 'http://localhost:1337/parse';
var res = await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, autoSendSessionId: true);
var connRes = await res.healthCheck();
var s = connRes.error?.message ?? "";
print("ERROR:" + s);
var firstObject = ParseObject('FirstClass')
..set(
'message', 'Hey ! First message from Flutter. Parse is now connected');
await firstObject.save();
print('done');
}
My error message:
SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = localhost, port = 35262
But for some unknown reason, I can not connect to my local server even if I can access with no problem my dashboard.
Your application running on the mobile device/emulator will treat localhost as own machine. In order to access the parse server running on your host machine (docker image exposing 0.0.0.0 global) you need to specify the host IP address.
Just replace const keyParseServerUrl = 'http://localhost:1337/parse'; with const keyParseServerUrl = 'http://YOUR_HOST_IP_ADDRESS:1337/parse'; provided in the docker parse server 0.0.0.0 should be exposed.

Why is my database not being cleared after each unit test?

I am trying to run a tests when no user is created and one can sign up for the first time. The test runs perfectly the first time and passes. The thing is that if I run it a second time, my container is not deleted properly and we end up with a HTTPStatus.conflict instead of .ok, so the user does already exist.
I am running a Docker container on my MacBook with docker-compose-testing, docker-compose and testing.Dockerfile set.
This error is also triggered when running the test:
caught error: "server: syntax error at end of input (scanner_yyerror)"
What is it missing here? Wouldn't autoRevert() and autoMigrate() clear my database?
func testSignUpRoute_userDoesNotExistInDatabase_userSignUpAndHTTPStatusIsOk() throws {
// Configuration in setUp and tearDown.
var app = Application(.testing)
defer { app.shutdown() }
try configure(app)
try app.autoRevert().wait()
try app.autoMigrate().wait()
// Given
let expected: HTTPStatus = .ok
let headers = [
"email": "foo#email.com",
"password": "fooEncrypted"
]
// When
try app.test(.POST, "users/signup") { request in
try request.content.encode(headers)
} afterResponse: { response in
let result = response.status
// Then
XCTAssertEqual(result, expected, "Response status must be \(expected)")
}
}
This is the order in which my migration happens in the configure.swift file:
public func configure(_ app: Application) throws {
app.migrations.add(UserModelMigration_v1_0_0())
app.migrations.add(AddressModelMigration_v1_0_0())
}
And the this is how I revert all my models. AddressModel and CompanyModel are #OptionalChild of the UserModel. It seems like the issue comes from here, but I can not point it out.
struct UserModelMigration_v1_0_0: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema(UserModel.schema)
.id()
.field(UserModel.Key.email, .string, .required)
.field(UserModel.Key.password, .string, .required)
.unique(on: UserModel.Key.email)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database
.schema(UserModel.schema)
.update()
}
}
struct AddressModelMigration_v1_0_0: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema(AddressModel.schema)
.id()
.field(AddressModel.Key.streetLineOne, .string, .required)
.field(AddressModel.Key.city, .string, .required)
.field(AddressModel.Key.userID, .uuid, .required,
.references(UserModel.schema, .id,
onDelete: .cascade,
onUpdate: .cascade))
.unique(on: AddressModel.Key.userID)
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database
.schema(AddressModel.schema)
.update()
}
}
This is my docker-compose-testing.yml file
version: '3'
services:
testingonlinux:
depends_on:
- postgres
build:
context: .
dockerfile: testing.Dockerfile
environment:
- DATABASE_HOST=postgres
- DATABASE_PORT=5434
postgres:
image: "postgres"
environment:
- POSTGRES_DB=foo_db_testing
- POSTGRES_USER=foo_user
- POSTGRES_PASSWORD=foo_password
This is my docker-compose.yml file
version: '3.8'
volumes:
db_data:
x-shared_environment: &shared_environment
LOG_LEVEL: ${LOG_LEVEL:-debug}
DATABASE_HOST: db
DATABASE_NAME: vapor_database
DATABASE_USERNAME: vapor_username
DATABASE_PASSWORD: vapor_password
services:
app:
image: FooServerSide:latest
build:
context: .
environment:
<<: *shared_environment
depends_on:
- db
ports:
- '8080:8080'
# user: '0' # uncomment to run as root for testing purposes even though Dockerfile defines 'vapor' user.
command: ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
migrate:
image: FooServerSide:latest
build:
context: .
environment:
<<: *shared_environment
depends_on:
- db
command: ["migrate", "--yes"]
deploy:
replicas: 0
revert:
image: FooServerSide:latest
build:
context: .
environment:
<<: *shared_environment
depends_on:
- db
command: ["migrate", "--revert", "--yes"]
deploy:
replicas: 0
db:
image: postgres:12-alpine
volumes:
- db_data:/var/lib/postgresql/data/pgdata
environment:
PGDATA: /var/lib/postgresql/data/pgdata
POSTGRES_USER: vapor_username
POSTGRES_PASSWORD: vapor_password
POSTGRES_DB: vapor_database
ports:
- '5432:5432'
And my testing.Dockerfile
FROM swift:5.5
WORKDIR /package
COPY . ./
CMD ["swift", "test", "--enable-test-discovery"]
The issue that stands out to me is that your revert methods don't seem to actually be deleting the data in the database or removing the table.
I have similar tests that use the revert functionality within Vapor and the migrations look like the following:
public struct ListV1: Migration {
public func prepare(on database: Database) -> EventLoopFuture<Void> {
return database.schema("Lists")
.id()
.field("listId", .int, .required, .custom("UNIQUE"))
.field("listString", .string, .required)
.field("createdAt", .datetime)
.field("updatedAt", .datetime)
.create()
}
public func revert(on database: Database) -> EventLoopFuture<Void> {
return database.schema("Lists").delete()
}
}
Changing your revert function to use .delete() (shown below) may resolve your issue:
struct AddressModelMigration_v1_0_0: Migration {
...
func revert(on database: Database) -> EventLoopFuture<Void> {
database
.schema(AddressModel.schema)
.delete()
}
}
Why don't you just put your App class in a var of your tests representing the sut (system under test) and override your test's setup() and tearDown() methods?
As in:
final class AppTests: XCTestCase {
var sut: Application!
override setup() {
super.setup()
sut = Application(.testing)
}
override tearDown() {
sut.shutdown()
sut = nil
super.tearDown()
}
// MARK: - Given
// MARK: - When
func whenMigrationsAreSet() async throws {
sut.migrations.add(UserModelMigration_v1_0_0())
sut.migrations.add(AddressModelMigration_v1_0_0())
sut.migrations.add(CompanyModelMigration_v1_0_0())
try await app.autoRevert()
try await app.autoMigrate()
}
// MARK: - Tests
func testSignUpRoute_whenUserDoesNotExist_thenUserSignUpAndHTTPStatusIsOk() async throws {
try await whenMigrationsAreSet()
let headers = [
"email": "foo#email.com",
"password": "fooEncrypted",
]
let requestExpectation = expectation("request completed")
let responseExpectation = expectation("got response")
var result: HTTPStatus?
try sut.test(.POST, "users/signup") { request in
try request.content.encode(headers)
requestExpectation.fullfill()
} afterResponse { response in
result = response.status
responseExpectation.fullfill()
}
wait(for: [requestExpectation, responseExpectation], timeout: 0.5, enforceOrder: true)
XCTAssertEqual(result, .ok)
}
}
Anyway I've also added expectations to your test since it seems it was doing some async work with completions in the old fashion.

Express app won't connect to docker postgres instance in production

I am building a webapp using express and postgres. For building my app I use the following files:
docker-compose.yml:
version: '3'
services:
postgres:
image: postgres:12
volumes:
- postgres-volume:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=${ADMIN_DB_PASSWORD}
networks:
- db
restart: unless-stopped
api:
build:
context: ./backEnd/
dockerfile: Dockerfile.debug
volumes:
- ./backEnd/index.js:/app/index.js
ports:
- "80:3002"
networks:
- db
depends_on:
- postgres
environment:
- DB_HOST=postgres
- DB_PORT=5432
- DB_DATABASE=hive
- DB_USER=${DB_API_USER}
- DB_PASSWORD=${DB_API_PASSWORD}
restart: unless-stopped
networks:
db:
The container runs the following code:
const express = require('express');
const bodyParser = require('body-parser')
const pgp = require('pg-promise')();
const connection = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
max: 30,
}
const db = pgp(connection);
function getUser(email){
return(
db.oneOrNone("SELECT * FROM users WHERE email = ${email}", {
email:email.toLowerCase()
})
)
}
const app = express();
app.use(bodyParser.json());
app.post('/login', async (req, res)=>{
const email = req.body.email;
console.log(email)
const user = await getUser(email);
console.log("made it past")
});
app.listen(3002, function () {
console.log('Listening on port 3002!');
});
When I call the login endpoint, it faithfully logs the email, but never gets past the
await getUser(email)
It does not throw and error or returns null, it just stays there. Interestingly it is working on my local machine and gets past the await, just not on my linux box.
I have also noticed, that if I change the db host to something nonsensical, pg-promise throws an error on my local machine. It does not however throw an error on my remote linux machine.
Also, if I run the script on the Linux box, without docker, it seamlessly connects to postgres. It appears to be something that only happens in conjunction with docker on Linux.
I am completely stumped by this error, as I have no indication of what is going wrong. The database also appears to be set up correctly, as I can connect to it and use it from my local machine with the same code.
Thank you in advance for your help.

ConnectionTimeoutException: No suitable servers found while inserting data into mongodb database

I am new in Docker and Mongodb.
I have following in my docker-compose.yml file.
version: '3.3'
services:
web:
build:
context: ./
dockerfile: Dockerfile
container_name: php73
volumes:
- ./src:/var/www/html/
ports:
- 8000:80
depends_on:
- db
networks:
- my-network
db:
image: mongo:latest
container_name: mymongo
restart: always
ports:
- '27017-27019:27017-27019'
networks:
- my-network
networks:
my-network:
Following file is run in php container. it just creates a database and insert some collectins into the database.
<?php
require 'vendor/autoload.php';
$myClient = new MongoDB\Client('mongodb://127.0.0.1:27017');
$mydb = $myClient->my_db;
$mycollection = $mydb->my_collection;
$insertData = $mycollection->insertOne([
'doc1' => 'abc',
'doc2' => 'def'
]);
?>
But, it shows following error:
PHP Fatal error: Uncaught MongoDB\\Driver\\Exception\\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling ismaster on '127.0.0.1:27017'] in /var/www/html/vendor/mongodb/mongodb/src/functions.php:431\nStack trace:\n#0 /var/www/html/vendor/mongodb/mongodb/src/functions.php(431): MongoDB\\Driver\\Manager->selectServer(Object(MongoDB\\Driver\\ReadPreference))\n#1 /var/www/html/vendor/mongodb/mongodb/src/Collection.php(929): MongoDB\\select_server(Object(MongoDB\\Driver\\Manager), Array)\n#2 /var/www/html/mycode.php(16): MongoDB\\Collection->insertOne(Array)\n#3 {main}\n thrown in /var/www/html/vendor/mongodb/mongodb/src/functions.php on line 431, referer: http://localhost:8000/index.php
I could not figure out why it is showing ConnectionTimeoutException.
Could anyone give any hints ?
Update your connection string to
<?php
require 'vendor/autoload.php';
$myClient = new MongoDB\Client('mongodb://db:27017');
// or new MongoDB\Client('mongodb://db:27017');
$mydb = $myClient->my_db;
$mycollection = $mydb->my_collection;
$insertData = $mycollection->insertOne([
'firstname' => 'abc',
'lastname' => 'def'
]);
?>
docker-compose create network by default, you can access other container using container name, where 127.0.0.1 refer to localhost of the php container, not DB container.

How to configure sonata user bundle

Alter update composer requirements got error
ServiceNotFoundException: The service "sonata.user.serializer.handler.user" has a dependency on a non-existent service "sonata.user.manager.user".
How to fix it?
In services.yml setup serializer service:
services:
sonata.user.serializer.handler.user:
class: Sonata\UserBundle\Serializer\UserSerializerHandler
tags:
- { name: jms_serializer.subscribing_handler }
arguments:
- [ sonata.user.mongodb.user_manager ]
It's need if you use MongoDb - seriaziler have default settings for ORM
You can also write this code in config/config.yml:
services:
sonata.user.serializer.handler.user:
class: Sonata\UserBundle\Serializer\UserSerializerHandler
tags:
- { name: jms_serializer.subscribing_handler }
arguments:
- [ sonata.user.mongodb.user_manager ]