Getting issue while fetching prev/next post from Sanity CMS ( Next js +Sanity static blog) - content-management-system

I'm using Sanity CMS, and trying to fetch previous and next post using this query below.
const query = `*[_type=='post' && slug.current == $slug][0]{
_id,title,_updatedAt,
"newPost" : *[_type == 'post' && ^._updatedAt > _updatedAt][0] {
title,"slug" : slug.current
}
}`;
const param = {
slug: "some-random-slug",
};
const nextPrev = await client.fetch(query, param);
My problem is that when I tried this above query at Sanity Vision, it works perfectly. But while trying this with sanity client, it doesn't return the newPost object. What's wrong with me?

Try this:
const query = `*[_type == "post" && slug.current == $slug][0] {
"nextPost": *[_type == "post" && ^._createdAt < _createdAt] | order(_createdAt asc)[0] {
// Fields
}
}`
const { nextPost } = await client.fetch(query, { slug })

Related

how to update a collection if you already called it MongoDB Mongoos

Ok so I have a problem in which I use a collection to gather some ratings data and work with it, by the time I finish the rating update process, I have new ratings that I would like to update the collection with. However I can't call update because I get the error "Cannot overwrite model once compiled." I understand that I already called once the model to work with the data and that's why I get the error. is there any way I can update the collection? Or I will just have to workaround by creating a new collection with the latest rating, and then matching the latest ratings collection with the one I use to work with the data.
This is my code
let calculateRating = async () => {
const getData = await matchesCollection().find().lean();
const playerCollection = await playersCollection();
const getDataPlayer = await playerCollection.find().lean();
let gamesCounting = [];
getDataPlayer.forEach((player) => {
player.makePlayer = ranking.makePlayer(1500);
});
for (let i = 0; i < getData.length; i++) {
const resultA = getDataPlayer.findIndex(({ userId }, index) => {
if (userId === getData[i].userA) {
return index;
}
});
const resultB = getDataPlayer.findIndex(
({ userId }) => userId === getData[i].userB
);
const winner = getData[i].winner;
if (getDataPlayer[resultA] === undefined) {
continue;
} else if (getDataPlayer[resultB] === undefined) {
continue;
}
gamesCounting.push([
getDataPlayer[resultA].makePlayer,
getDataPlayer[resultB].makePlayer,
winner,
]);
}
ranking.updateRatings(gamesCounting);
let ratingsUpdate = [];
getDataPlayer.forEach((item) => {
let newRating = item.makePlayer.getRating();
let newDeviation = item.makePlayer.getRd();
let newVolatility = item.makePlayer.getVol();
item.rating = newRating;
item.rd = newDeviation;
item.vol = newVolatility;
ratingsUpdate.push(item);
});
};
I try the work around with creating the new collection

Discourse plugin to restrict users from mentioning each other is failing

I have inherited a plugin used to restrict #mentions in discourse. Users are restricted to specific categories and are unable to view blocked categories, but when using the #mention in a topic the users in the restricted categories are showing up.
So user A works at company 1 and has access to the category associated to company 1. User B has access to the company 2 category. When user A #mentions someone on the company 1 category the autocomplete is displaying the users associated with the company 2 category.
I'm receiving no errors and the plugin supposedly worked before my arrival.
import { withPluginApi } from "discourse/lib/plugin-api";
import discourseComputed from "discourse-common/utils/decorators";
import userSearch from "discourse/lib/user-search";
function initWithApi(api) {
if (!Discourse.SiteSettings.restrict_mentions_enabled) return;
api.modifyClass("component:groups-form-interaction-fields", {
pluginId: 'groups-form-interaction-fields-plugin',
#discourseComputed(
"siteSettings.restrict_mentions_enabled",
"currentUser.admin",
"model.c_all_groups",
"model.name"
)
isShowRestrictMentions(enabled, admin, allGroups, name) {
return enabled && admin && allGroups && name && allGroups.includes(name);
},
#discourseComputed("model.c_all_groups", "model.name")
cSelectableGroups(allGroups, name) {
return (allGroups || []).filter(g => g !== name);
},
actions: {
setCAllowedMentionGroups(val) {
console.log(val);
let newVal;
if (val.includes("any")) {
newVal = "any";
} else {
newVal = val.filter(x => !Ember.isBlank(x)).join("|");
}
console.log(newVal)
this.model.set("c_allowed_mention_groups", newVal);
}
}
});
api.modifyClass("model:group", {
pluginId: 'group-plugin',
asJSON() {
const attrs = this._super(...arguments);
attrs["c_allowed_mention_groups"] = this.c_allowed_mention_groups;
return attrs;
},
#discourseComputed("c_allowed_mention_groups")
cAllowedMentionGroups(groups) {
return (groups || "").split("|");
}
});
api.modifyClass("component:composer-editor", {
pluginId: 'composer-editor-plugin',
userSearchTerm(term) {
if (!this.siteSettings.restrict_mentions_enabled) {
return this._super(...arguments);
}
let viewGroups = true;
const allowed =
this.get("topic.c_allowed_mention_groups") ||
this.currentUser.get("c_allowed_mention_groups");
console.log([this, allowed]);
if (Ember.isBlank(allowed)) {
return;
}
//REMOVING CUSTOMER GROUP FROM SEARCHABLE ARRAY OF STANDARD USERS
if(!this.currentUser.admin && !this.currentUser.moderator){
viewGroups = false;
const index = allowed.indexOf('All_Customers');
if (index > -1) {
allowed.splice(index, 1);
}
console.log(allowed)
}
const opts = {
term,
includeGroups: viewGroups,
groupMembersOf: allowed
};
return userSearch(opts);
}
});
}
export default {
name: "restrict-mentions",
initialize() {
withPluginApi("0.8", initWithApi);
}
};

Flutter get all images from website with given URL

I am trying to scrape any website for its images and save them in a list. For that I am using the getElementsByTagname("img") and also selected the ['src'] attributes like this:
void _getData() async {
final response = await http.get(Uri.parse(_currentUrl));
final host = Uri.parse(_currentUrl).host;
dom.Document document = parser.parse(response.body);
final elements = document.getElementsByTagName("img").toList();
for (var element in elements) {
var imageSource = element.attributes['src'] ?? '';
print(imageSource);
bool validURL = Uri.parse(imageSource).host == '' ||
Uri.parse(host + imageSource).host == ''
? false
: true;
if (validURL && !imageSource.endsWith('svg')) {
Uri imageSourceUrl = Uri.parse(imageSource);
if (imageSourceUrl.host.isEmpty) {
imageSource = host + imageSource;
}
if (_imagesWithSize.firstWhereOrNull(
(element) => element.imageUrl == imageSource,
) ==
null) {
Size size = await _calculateImageDimension(imageSource);
_imagesWithSize.add(
ImageWithSize(
imageSource,
size,
),
);
}
}
}
_imagesWithSize.sort(
(a, b) => (b.imageSize.height * b.imageSize.width).compareTo(
a.imageSize.height * a.imageSize.width,
),
);
}
Problem:
This does not work with this link:
HM Productlink
I get this URL:
//lp2.hm.com/hmgoepprod?set=quality%5B79%5D%2Csource%5B%2F0c%2Fe6%2F0ce67f87aa6691557f30371590cf854ed0fb77c7.jpg%5D%2Corigin%5Bdam%5D%2Ccategory%5B%5D%2Ctype%5BLOOKBOOK%5D%2Cres%5Bm%5D%2Chmver%5B1%5D&call=url[file:/product/main]
And this is not a valid URL...
How can I parse the image from this website?
Let me know if you need any more info!
Links with leading double slashes are valid in HTML, as part of RFC1808. They will be replaced by http or https depending on the context. It will probably work if you add the scheme (http: or https:) from _currentUrl to imageSourceUrl.
I have not tested this, but I assume something like this would work:
if (!imageSourceUrl.hasScheme) {
final scheme = Uri.parse(_currentUrl).scheme;
imageSourceUrl = imageSourceUrl.replace(scheme: scheme);
}

MongoDB function and how to call it?

I'm new to MongoDB and I found this function on the web. it's going to work for my all queries.
For settings.amount, settings.balance etc..
exports.updateUsers = function ( user_id, where, what, pass ) {
var _where = 'settings.'+where; //when I use it doesn't update
var update = {};
update[_where] = what;
user.findOneAndUpdate(
{'user_id' : user_id},
update).exec(function(e,d){
pass("ok")
})
};
Could anyone explain to me how can I call this query to update balance or amount?
Could anyone give me an example of updating something?
You can use it like this:
const { updateUsers } = require('./pathToFile.js'); // add the correct path;
// assuming you want to update the balance of a user to 69
updateUsers('some id', 'balance', 69, (result) => {
if(result === 'ok') {
// do something
} else if(result === 'bad') {
// you have an error
}
})
I would also change updateUsers to handle errors:
exports.updateUsers = function (user_id, where, what, pass) {
var _where = 'settings.' + where; //when I use it doesn't update
var update = {};
update[_where] = what;
user.findOneAndUpdate(
{ 'user_id': user_id },
update).exec(function (error, d) {
if (!error) {
pass('ok');
} else {
pass('bad')
}
})
};

How can i perform not contains query in sequelize

I'm using sequelize with postgres,
Is there a way to perform a "not contains" statement with sequelize?
something like:
[Op.not]: {
[Op.contains]: ['value1','value2']
}
which produces:
SELECT * FROM Table WHERE NOT ArrayColumn #>ARRAY['value1','value2']::VARCHAR(255)[]
had the same issue had to go to rawish SQL
where['<COL_NAME>'][Op.and] = [Sequelize.literal(`'${JS_VARIABLE_ARRAY}' != all (<COL_NAME>)`)];
I've built this helper function to construct the my where query
const buildWhereQuery = (query, columns) => {
const parsedObject = {};
Object.keys(query).forEach((attr) => {
if (columns.indexOf(attr) !== -1 && (query[attr] !== null || query[attr] !== undefined)) {
parsedObject[attr] = query[attr];
}
});
return parsedObject;
};
const where = buildWhereQuery(query, columnsToQueryAgainst)
hope that's help.
using:
node: v10.14.2
sequelize#4.38.0
sequelize-cli#4.0.0
You can use as
where: {
$not: { $contains: ['value1','value2'] },
}