How to find an array larger than 0, in typeorm? - typeorm

Hi this is how my Postgres looks like
header is exampleHeader
[{test: 'hi'}] full
null empty
How do I filter andWhere to take out any results that are not full?
I tried the following:
const res = await this.testRepository
.createQueryBuilder('ts')
.where('ts.user_id = :id', { id })
.andWhere('ts.exampleHeader >: num', { num: 0 });

const res = await this.testRepository
.createQueryBuilder('ts')
.where('ts.user_id = :id', { id })
.andWhere(`jsonb_array_length(ts.exampleHeader) >0`);
The above worked for me

Related

Single sign on failing with LinkedIn account to a microsoft website

We are seeing an issue with users unable to access our production and PPE apps via LinkedIn sign in. The redirection is not happening to specified redirect URL once users provides user name and password. The network trace shows login is successful but not going to redirect URL. This has been working last 4 years or so and suddenly started failing in both environments from yesterday.
Bummer. Something went wrong
We tried verifying the network trace and a support case is raised to LinkedIn with recording. Finally we are redirected to raise the issue here.
I had the same issue and found that it was caused by using JSON.stringify to "overload" the state parameter with other parameters. In my case, I add other parameters in the following way:
providerCfg.auth_params.state = JSON.stringify({
state: providerCfg.auth_params.state,
redirectPageUrl,
redirectParams,
userTypeBit,
isLogin
})
const authUrl = new URL(providerCfg.auth_url)
Object.entries(providerCfg.auth_params).forEach(([key, val]) => {
authUrl.searchParams.append(key, encodeURIComponent(val))
})
return buildURL(providerCfg.auth_url, providerCfg.auth_params)
When I removed the call to JSON.stringify and just passed in a state parameter, the oauth flow worked correctly. Obviously, the other parameters that I passed in were important so I created my own functions to serialize and deserialize the values. The code below works well for anything other than deeply nested objects. You will need to update the metaDataCfg based on your own requirements.
const META_STRING_DELIMITER = '|'
const serializeBasicObject = (targetObj) => {
if (!targetObj) {
return ''
}
return Object.entries(targetObj).reduce((objString, [key, val]) => {
const param = `${key}=${val || ''}`
if (!objString.length) {
return param
}
return `${objString}${META_STRING_DELIMITER}${param}`
}, '')
}
const deserializeBasicObject = (targetStr) => {
if (!targetStr) {
return ''
}
const keyValPairs = targetStr.split(META_STRING_DELIMITER)
return keyValPairs.reduce((targetObj, keyValPair) => {
const splitIdx = keyValPair.indexOf('=')
const key = keyValPair.slice(0, splitIdx)
targetObj[key] = keyValPair.slice(splitIdx + 1, keyValPair.length)
return targetObj
}, {})
}
const metaDataCfg = {
state: {},
redirectPageUrl: {},
redirectParams: {
serialize: serializeBasicObject,
deserialize: deserializeBasicObject
},
userTypeBit: { deserialize: Number },
isLogin: { deserialize: dataUtil.getBoolean }
}
const getMetaString = (metaData) => {
return Object.entries(metaDataCfg).reduce((metaString, [metaDataKey, cfg]) => {
const val = (cfg.serialize) ? cfg.serialize(metaData[metaDataKey]) : metaData[metaDataKey]
const param = `${metaDataKey}=${dataUtil.isNil(val) ? '' : val}`
if (!metaString.length) {
return param
}
return `${metaString}${META_STRING_DELIMITER}${param}`
}, '')
}
export const getDataFromMetaString = (metaString) => {
const params = metaString.split(META_STRING_DELIMITER)
const data = params.reduce((metaData, param) => {
const splitIdx = param.indexOf('=')
const key = param.slice(0, splitIdx)
let val = param.slice(splitIdx + 1, param.length)
if (dataUtil.isNil(val) || !val.length) {
return metaData
}
const deserializer = metaDataCfg[key].deserialize
if (deserializer && val) {
val = deserializer(val)
}
metaData[key] = val
return metaData
}, {})
return data
}

How do you query using an index in the Architect Serverless Framework?

I am trying to query using an index but keep getting this error:
ValidationException: Query condition missed key schema element: trackID
Here is my .arc file
#tables
skytracks
trackID *String
_ttl TTL
#indexes
skytracks
skyTrackType *String
Here is the relevant piece of the http get handler:
const skyTrackType = req.queryStringParameters.skytracktype
const data = await arc.tables()
const trackingData = await data.skytracks.query({
KeyConditionExpression: `skyTrackType = :skyTrackType`,
ExpressionAttributeValues: {
':skyTrackType': skyTrackType
}
})
Architect automatically names the index attribute-index
This needs to be added to the query in the question: IndexName: 'skyTrackType-index'
const trackingData = await data.skytracks.query({
KeyConditionExpression: `skyTrackType = :skyTrackType`,
IndexName: 'skyTrackType-index',
ExpressionAttributeValues: {
':skyTrackType': skyTrackType
}
})

Looping through custom fields to populate dynamic fields in Zapier

I'm not sure how to loop through the custom fields when adding a dynamic field via the web script editor.
When I test I can see the fields are being returned in the console
Where the number of fields is different with each instance of our app.
This is the code I'm using to return the data.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
return results;
});
I assume I need to loop through each of the fields, pull out the ID and name and then put them back as an array of objects?
Something like this, only problem is nothing is being returned?
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content).results._embedded;
var cFields = [];
for (var i = 0; i < results.length; i++) {
cFields.push({'id': results.customFields[i].label});
}
return cFields;
});
Any pointers?
I worked this out in the end. I think the problem was more because of my lack of coding knowledge. Not sure if this is the best answer but it worked.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
let customFields = [];
for (let i = 0; i < results.customFields.length; i++) {
let customFieldsObj = {};
customFieldsObj['key'] = results.customFields[i].id;
customFieldsObj['label'] = results.customFields[i].label;
let helpText = results.customFields[i].type + ' Field';
customFieldsObj['helpText'] = helpText.toUpperCase();
customFields.push(customFieldsObj);
}
return customFields;
});

launch many transactions typeorm into loop javascript

In my Electron App I would like to inject data (like Fixtures) when App launched.
I use typeorm library for managing my SQLite3 Database connection.
I created json file that represent Entity typeorm and I would like persist all of them in my DB with typeorm. For that It seems that use trasaction is more efficient.
I try two differents things but the result is the same and I don't uderstand why. The issue message is :
Error: Transaction already started for the given connection, commit
current transaction before starting a new one
My first implementation of transaction :
async setAll(entity, data)
{
let connection = await this.init()
const queryRunner = connection.createQueryRunner()
await queryRunner.connect()
for (const [key, value] of Object.entries(data))
{
await typeorm.getManager().transaction(transactionalEntityManager =>
{
})
}
}
My second implementation of transaction :
async setAll(entity, data)
{
let connection = await this.init()
const queryRunner = connection.createQueryRunner()
await queryRunner.connect()
for (const [key, value] of Object.entries(data))
{
let genre1 = new Genre()
genre1.name = 'toto'
genre1.identifier = 'gt'
genre1.logo = ''
genre1.isActivate = false
await queryRunner.startTransaction()
await queryRunner.manager.save(genre1)
await queryRunner.commitTransaction()
await queryRunner.release()
}
}
NB : The second implementation persist correctly the first object but not the others.
How can manage many typeorm Transaction created into loop for persist lot of data ?
async setAll(entity, data) {
let connection = await this.init()
const queryRunner = connection.createQueryRunner()
await queryRunner.connect()
await queryRunner.startTransaction()
try {
for await (const [key, value] of Object.entries(data)) {
let genre1 = new Genre()
genre1.name = 'toto'
genre1.identifier = 'gt'
genre1.logo = ''
genre1.isActivate = false
const newGenre= queryRunner.manager.create(Genre,genre1)
await queryRunner.manager.save(newGenre)
}
await queryRunner.commitTransaction()
} catch {
await queryRunner.rollbackTransaction()
} finally {
await queryRunner.release()
}

odata TreeTable with empty row because of slash?

I have a TreeTable which shows data from oData service. Some of the data fields contains symbols of slash ("/", f.e. cats/dogs). My service understands them like a new kind of parameter and doesn't display them in a TreeTable (gives a blank row).
Here is my code:
oData = new sap.ui.model.odata.ODataModel(".../categories/categories.xsodata/", false);
oData.read("/Categories/",
null,
null,
false,
function(oData, oResponse){
flat = {};
for (var i = 0; i < oData.results.length; ++i) {
var item, group, type, code;
var getSubNode = function(obj, key) {
if (!obj[key]) {
obj[key] = {'NAME': key}
}
return obj[key];
};
item = oData.results[i];
group = getSubNode(flat, item.PET_GROUP);
type = getSubNode(group, item.PET_TYPE);
item.NAME = item.GENDER;
item.__metadata = "";
type[item.GENDER] = item;
}
data = {flat : flat,};
});
ojModel = new sap.ui.model.json.JSONModel();
ojModel.setData(data);
oTable.setModel(ojModel);
oTable.bindRows("/flat");
return oTable;
Maybe there is a solution for this?

Resources