Set default value for CfnParameter when left empty in CDK - aws-cloudformation

I have a CDK project and I need to have input parameters and some of them have to be optional.
In my code I need to have a value in any case, so I'm looking a way to set a value if the user left the field empty.
I found some things with Fn.conditionIf and CfnCondition but I don't understand how to use them to achieve what I want.
Here is what I have:
const param1 = new CfnParameter(this, "Param1", {
type: "String",
description: "Myparam",
});
Later on my code I'm getting the value and here I need to set something if is empty:
var myObj = {
myParamFromUser: param1.valueAsString,
};
If I use default value field, that value is displayed on the Console and the field has already the value. I want to have the field empty on the Console.
How to set a value if param1 is empty?

I made it work:
const myCfnParam = new CfnParameter(this, "Param", {
type: "String",
description:
"Input param",
});
const myCondition = new CfnCondition(this, 'Condition', { expression: Fn.conditionEquals(myCfnParam, '') });
const myValue= Fn.conditionIf(myCondition.logicalId, 'MY_STRING', myCfnParam.valueAsString).toString();

Related

omit empty strings fields mongoose

I have the following schema:
const mySchema = new mongoose.Schema({
x: String,
y: String
})
when a user from the front-end requests in his body:
req.body = {
'x' : '',
'y': ''
}
this results in creating a field in MongoDB, but with an empty string.
I need a way to prevent this behavior by setting the empty strings to be undefined somehow.
Is there such an option in Mongoose? or do I have to predict my own middlewares for that?
You could use the set method for Mongoose Schemas:
const mySchema = new mongoose.Schema(
{
myAttribute: {
type: String,
set: (attribute: string) => attribute === '' ? undefined : attribute,
},
},
{ strict: 'throw' },
);
This will unset the field if the string equals ''.
Use this to trim the strings:
set: (a: string) => a?.trim() === '' ? undefined : a
You don't need mongoose, or a middleware to handle this. You can just write a quick few lines to check for empty values and exclude them from the MongoDB write operation.
Ex:
const newEntry = Object.entries(req.body).reduce((obj, [key, value]) => {
if (value) obj[key] = value
return obj
}, {})
In this example, I convert the req.body into an array using Object.entries and iterate over it with the Array.reduce method, wherein I add key:value pairs to a new object if there is a value to add. Since an empty string value is falsey I can do a simple if check on the value. I then assign the return of the reduce method to the variable newEntry. Then I would then take the new entry and create the MongoDB document with it.
This could be extracted into a helper method and reused in any of your routes that need to check remove empty values from an object.
Docs on Array.reduce
Docs on Object.entries

SAPUI5 : Table search field not working on defined values

I have a parameter Type which is coming as Integer. If Type is 0 we show "Protect" otherwise Unprotect
My Controller is something like this
new Column({
label: new Label({text: "Type"}),
template: new Label({text:
{
path: "ruleType",
formatter: function (value) {
if(parseInt(value) === 0)
return "Protect";
else
return "Unprotect";
}
}}),
filterProperty: "ruleType"
})
My View is something like this
var vQuery = oEvent.getParameter("searchparam");
new Filter({
path: 'ruleType',
operator: FilterOperator.Contains,
value1: vQuery
}),
I have 2 issues
Uncaught Error: Only "String" values are supported for the FilterOperator: "Contains".
When I search with search value : "Protect" filter is not working.
I tried changing FilterOperator.Contains to FilterOperator.EQ string error is gone but search with "Protect" is not working. Can someone help
You can write a custom test function (I always convert the string and search query to lower case).
var vQuery = oEvent.getParameter("searchparam").toLowerCase();
new Filter({
path: 'ruleType',
test: function(value){
return value.toLowerCase().indexOf(vQuery) > -1 //returns true/false
}
});

How to set new fields default value in mongodb?

I have had a mongoose schema like below:
var schema = mongoose.Schema({
name: String
}
I had some documents with these schema and after a while I've added a new field with a default value :
var schema = mongoose.Schema({
name: String,
job: {type: String, default: function() { return "Job" + this.name.toLowerCase() }}
}
When I get the document (findOne), I can see the default value be set. But when I check the exact row in my database, default value is not set yet!
When I add new documents, the default value is set and everything is alright; but how can I make the old documents' default value be set in database?
Try to updated your old documents using hook :
schema.post('init', function (doc) {
if(!doc.job){
doc.job = "Job" + doc.name.toLowerCase();
doc.save();
}
});

must have a selection of subfields. Did you mean \"createEvent { ... }\"?", [graphql] [duplicate]

Hi I am trying to learn GraphQL language. I have below snippet of code.
// Welcome to Launchpad!
// Log in to edit and save pads, run queries in GraphiQL on the right.
// Click "Download" above to get a zip with a standalone Node.js server.
// See docs and examples at https://github.com/apollographql/awesome-launchpad
// graphql-tools combines a schema string with resolvers.
import { makeExecutableSchema } from 'graphql-tools';
// Construct a schema, using GraphQL schema language
const typeDefs = `
type User {
name: String!
age: Int!
}
type Query {
me: User
}
`;
const user = { name: 'Williams', age: 26};
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
me: (root, args, context) => {
return user;
},
},
};
// Required: Export the GraphQL.js schema object as "schema"
export const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// Optional: Export a function to get context from the request. It accepts two
// parameters - headers (lowercased http headers) and secrets (secrets defined
// in secrets section). It must return an object (or a promise resolving to it).
export function context(headers, secrets) {
return {
headers,
secrets,
};
};
// Optional: Export a root value to be passed during execution
// export const rootValue = {};
// Optional: Export a root function, that returns root to be passed
// during execution, accepting headers and secrets. It can return a
// promise. rootFunction takes precedence over rootValue.
// export function rootFunction(headers, secrets) {
// return {
// headers,
// secrets,
// };
// };
Request:
{
me
}
Response:
{
"errors": [
{
"message": "Field \"me\" of type \"User\" must have a selection of subfields. Did you mean \"me { ... }\"?",
"locations": [
{
"line": 4,
"column": 3
}
]
}
]
}
Does anyone know what I am doing wrong ? How to fix it ?
From the docs:
A GraphQL object type has a name and fields, but at some point those
fields have to resolve to some concrete data. That's where the scalar
types come in: they represent the leaves of the query.
GraphQL requires that you construct your queries in a way that only returns concrete data. Each field has to ultimately resolve to one or more scalars (or enums). That means you cannot just request a field that resolves to a type without also indicating which fields of that type you want to get back.
That's what the error message you received is telling you -- you requested a User type, but you didn't tell GraphQL at least one field to get back from that type.
To fix it, just change your request to include name like this:
{
me {
name
}
}
... or age. Or both. You cannot, however, request a specific type and expect GraphQL to provide all the fields for it -- you will always have to provide a selection (one or more) of fields for that type.

How can I access a date typed field from an ExtJS JSonStore?

I've been trying to retrieve a date value and an integer value from the database, using the following code:
var l_alsChampsMois, l_stoDonneesMois;
try {
l_alsChampsMois = [
{name: "date_mois", type: "date", dateFormat: "Y-m-d"},
{name: "indice", type: "integer"}
];
l_stoDonneesMois = new Ext.data.JsonStore({
fields: l_alsChampsMois,
autoLoad: false,
proxy: {
type: "ajax",
url: "/commun/req_sql/req_ind_per_mois.php",
reader: {
type: "json",
root: "rows"
},
// some configs to use jsFiddle echo service (you will remove them)
actionMethods: {
read: "POST"
},
extraParams: {
key:"test"
}
},
listeners: {
load: function(objStore, alsLignes, blnOk, objOptions) {
window.alert("Mois fin : " + objStore.getAt(0).get("date_mois"));
}
}
});
l_stoDonneesMois.load({params: {
p_idsoc: l_strIdSociete,
p_mois: l_datDebut.getMonth() + 1,
// getMonth renvoie 0 pour janvier, etc.
p_annee: l_datDebut.getFullYear(),
p_debut: 1,
p_etape: 1
}
});
with l_strIdSociete and l_datDebut being variables previously assigned and /commun/req_sql/req_ind_per_mois.php the PHP page that retrieves the data and converts it to JSON.
It seems to work fine (indeed, Firebug tells me the load does retrieve a data structure with "date_mois" and "indice" containing the values I expect them to), only the window.alert returns undefined. If I replace "date_mois" with "indice", it returns the expected value for "indice".
I've tried to use objStore.getAt(0).getData()["date_mois"], to no avail.
My only clue about this is that "date_mois" in the data structure shown by Firebug is an Object, but even so it shouldn't be undefined, now should it? I looked up http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Field-cfg-type that wasn't exactly forthcoming with straight answers.
So what did I do wrong there?
If you need current time you can use php time function(note: it returns seconds, JS uses milliseconds), in another case you need to convert by mktime function.