ionic2 modal error no data sending - mongodb

When i use alertCtrl like this data is going to db it's working well.
addTodo(){
let prompt = this.alertCtrl.create({
title: 'add',
message: 'add',
inputs: [
{
name: 'title'
},
{
name: 'kan'
},
{
name: 'geos'
},
{
name: 'geod'
},
{
name: 'sahip'
}
],
buttons: [
{
text: 'İptal'
},
{
text: 'Kaydet',
handler: todo => {
if(todo){
this.showLoader();
this.todoService.createTodo(todo).then((result) => {
this.loading.dismiss();
this.todos = result;
console.log("todo created");
}, (err) => {
this.loading.dismiss();
console.log("not allowed");
});
}
}
}
]
});
prompt.present();
}
But when i try to use modal , showloader is running but createtodo is not working , no data is going to db .
addTodo(){
let modal = this.modalCtrl.create(KaneklePage);
modal.onDidDismiss(todo => {
if(todo){
this.showLoader();
this.todoService.createTodo(todo).then((result) => {
this.loading.dismiss();
this.todos = result;
console.log("todo created");
}, (err) => {
this.loading.dismiss();
console.log("not allowed");
});
}
});
modal.present();
}
This is dismiss code in modalpage
save(): void {
let todo = {
title: this.title,
kan: this.kan,
geos: this.geos,
geod: this.geod,
sahip: this.sahip
};
this.viewCtrl.dismiss(todo);
}

Related

How to properly define a CodeMirror language?

I'm trying to provide a basic autocompletion for something like this:
db.collection("Items").where("name", "==", "temp").limit(1).get();
Here's the code I have so far, using StreamLanguage of CodeMirror 6:
import {
IndentContext,
LanguageSupport,
StreamLanguage,
StringStream
} from "#codemirror/language";
import { tags as t } from "#lezer/highlight";
export const FireStoreLanguage = StreamLanguage.define({
name: "firestore",
startState: (indentUnit: number) => {
return {};
},
token: (stream: StringStream, state: any = {}): string | null => {
console.log(stream);
if (stream.match("db")) {
state.db = true;
return "keyword";
}
if (stream.match(".")) {
if (state.db) {
state.db = false;
state.collection = true;
return "keyword";
} else if (state.collection) {
state.collection = false;
state.where = true;
return "keyword";
} else if (state.where) {
state.where = false;
state.limit = true;
return "keyword";
} else if (state.limit) {
state.limit = false;
return "keyword";
}
}
if (stream.match("collection")) {
if (state.db) {
state.collection = true;
return "keyword";
}
}
if (stream.match("where")) {
if (state.collection) {
state.where = true;
return "keyword";
}
}
if (stream.match("limit")) {
if (state.where) {
state.limit = true;
return "keyword";
}
}
if (stream.match("get")) {
if (state.limit) {
state.limit = false;
return "keyword";
}
}
if (stream.match(/"(?:[^\\"]|\\.)*"/)) {
if (state.collection) {
return "string";
}
if (state.where) {
state.where = false;
state.whereValue = true;
return "string";
}
if (state.whereValue) {
state.whereValue = false;
return "string";
}
if (stream.match("==")) {
if (state.whereValue) {
state.whereValue = false;
state.whereOperator = true;
return "operator";
}
}
if (stream.match(/[0-9]+/)) {
if (state.limit) {
return "number";
}
}
}
stream.next();
return null;
},
blankLine: (state: {}, indentUnit: number): void => {},
copyState: (state: {}) => {},
indent: (
state: {},
textAfter: string,
context: IndentContext
): number | null => {
return 1;
},
languageData: {
commentTokens: { line: ";" },
},
tokenTable: {
db: t.keyword,
dot: t.punctuation,
collection: t.keyword,
get: t.keyword,
lParen: t.punctuation,
rParen: t.punctuation,
string: t.string,
},
});
export function firestore() {
return new LanguageSupport(FireStoreLanguage);
}
In React, here's how I use it(after building it):
import CodeMirror from "#uiw/react-codemirror";
import React from "react";
import { firestore } from "./firestore";
function App() {
const onChange = React.useCallback((value, viewUpdate) => {
console.log("value:", value);
}, []);
return (
<CodeMirror
value={``}
height="100vh"
extensions={[firestore()]}
onChange={onChange}
/>
);
}
export default App;
The editor loads okay, but no autocompletion is provided while I type!
What am I doing wrong or missing in the code above?
I was missing these parts:
export const FireStoreCompletion = FireStoreLanguage.data.of({
autocomplete: completeFromList([
{ label: "db", type: "namespace" },
{ label: "collection", type: "function" },
{ label: "where", type: "function" },
{ label: "limit", type: "function" },
{ label: "get", type: "function" },
]),
});
export function firestore() {
return new LanguageSupport(FireStoreLanguage, [FireStoreCompletion]);
}

Updating array of objects in Mongoose

I can't handle updating array of objects in my database, tried many options but nothing worked. Im pretty sure that the answer is obvious, but I couldn't manage it since wednesday.
Here is my kitSchema:
const kitSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
kit: {
type: Array,
required: true,
},
profiles: {
type: Array,
required: true,
},
});
module.exports = mongoose.model("Kit", kitSchema);
All users have their own document, and there are also profiles in it. I want to update single profile by passing the id of user and id of profile.
Example of data:
_id: 1,
email: "abc#mail",
password: "abc",
profiles: [
{
id: 1,
name: John
},
]
And here's my latest solution which doesn't work:
router.put("/profile/:id", async (req, res) => {
let kit = await Kit.findById(req.params.id, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
});
try {
await kit.profiles.findOneAndUpdate(
{ id: req.body.id },
{ name: req.body.name },
{ new: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
} catch (err) {
res.status(400).json({ message: err });
}
});
Could you give me a hand with this?
As always, after days of trying I've got answer 10 minutes after asking question. Here's what I came up with:
router.put("/profile/:id", async (req, res) => {
await Kit.findOneAndUpdate(
{ _id: req.params.id, profiles: { $elemMatch: { id: req.body.id } } },
{
$set: {
"profiles.$.name": req.body.name,
"profiles.$.profilePicture": req.body.profilePicture,
},
},
{ new: true, safe: true, upsert: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
});

ERROR in Read query using n AWS AppSync Chat Starter App written in Angular "Can't find field allMessageConnection"

const message: Message = {
conversationId: conversationId,
content: this.message,
createdAt: id,
sender: this.senderId,
isSent: false,
id: id,
};
this.appsync.hc().then((client) => {
client
.mutate({
mutation: createMessage,
variables: message,
optimisticResponse: () => ({
createMessage: {
...message,
__typename: "Message",
},
}),
update: (proxy, { data: { createMessage: _message } }) => {
const options = {
query: getConversationMessages,
variables: {
conversationId: conversationId,
first: constants.messageFirst,
},
};
// error on below line
const data = proxy.readQuery(options);
const _tmp = unshiftMessage(data, _message);
proxy.writeQuery({ ...options, data: _tmp });
},
})
.then(({ data }) => {
console.log("mutation complete", data);
console.log("mutation complete", data);
})
.catch((err) => console.log("Error creating message", err));
});
Analytics.record("Chat MSG Sent");
}
ERROR
errorHandling.js:7 Error: Can't find field allMessageConnection({"conversationId":"XXXXXXXXXXXXXXXXXXXXXXXXXXX","first":100}) on object {
"me": {
"type": "id",
"generated": false,
"id": "User:XXXXXXXXXXXXXXXXXXX",
"typename": "User"
}
}.

Updating aws apigateway binaryMediaTypes with javascript SDK

If I want to configure the binaryMediaTypes [ 'image/jpg', 'text/html' ] for an API through nodejs. What is the right API to use? It looks like the below is not working.
const config = JSON.stringify({
"swagger": "2.0",
"info": {
"title": this.apiName
},
"x-amazon-apigateway-binary-media-types": [ 'image/jpg', 'text/html' ]
});
return new Promise((resolve, reject) => {
var params = {
restApiId: apiId, /* required */
mode: 'merge',
body: config
};
this.apiGatewaySDK.putRestApi(params, (err, data) => {
if (err) {
reject(err);
}
else {
resolve('binary set successfully');
}
});
});
we end up using updateRestApi(). Pls note the patchOpertions part, it is very unintuitive (sth aws sdk could improve? )
let patchOperationsArray = [];
patchOperationsArray.push(
{
op: 'add',
path: '/binaryMediaTypes/'+ e.replace("/", "~1")
}
);
const params = {
restApiId: apiId, /* required */
patchOperations:patchOperationsArray
};
this.apiGatewaySDK.updateRestApi(params, (err, data) => {
if (err) {
reject(err);
}
else {
this.serverless.cli.log('API Gateway Configuring: Binary support are set correctly');
resolve('binary set successfully');
}
});

Ionic Alert: Wait until button is pressed

I have a class Action with it's method do() wherein the IonicAlert is called.
What I want to do now is, that I call something like
Action.do().then( () => { /* do domething */ } );
but only after OK was clicked on the alert.
do(): Promise<boolean> {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then( () => { /* do something */ });
return false;
}
}]
});
alert.present();
return null;
}
}
I added return null; only to get no error, but of course it's not working.
Any idea, how to solve this? Thanks
PS: I also posted it to the ionic forum: https://forum.ionicframework.com/t/ionic-alert-wait-until-button-is-pressed/67448
Found the solution with the help of this site: https://basarat.gitbooks.io/typescript/content/docs/promise.html
do(): Promise<boolean> {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then(() => { resolve(true); });
return false;
}
}]
});
alert.present();
});
}
}
Here a version who can return true or false :
showConfirm(): Promise<boolean> {
return new Promise((resolve, reject) =>{
const confirm = this.alertCtrl.create({
title : 'Are you sure ?',
buttons: [
{
text: 'Yes',
handler:_=> resolve(true)
},
{
text: 'No',
handler:_=> resolve(false)
}
]
}).present();
})
}
To call the promise :
this.showConfirm().then((result) => {
if(result){
// do something
}
})
This works for me
handler: () => {
console.log(this.viewCtrl.dismiss());
}
That code didn't work for me in Ionic4. This did:
presentAlert():Promise<boolean> {
return new Promise((resolve, reject) => {
const ctl = this.alertController;
let alert:any = this.alertController.create({
buttons: [{
text: 'OK',
handler: () => {
ctl.dismiss().then(() => { resolve(true); });
return false;
}
}]
}).then((dlg) => dlg.present());
});
}