r.db('dbname').table('urls').filter(function(url) {
return url("expires_at").date().eq(r.now().date())
.and(url("expires_at").hours().eq(r.now().hours().sub(1)))
});
I am trying to write the equivalent query using thinky ORM for node.js
I've never worked with Thinky, but according to docs, you should create model and make query on it.
1) Create model. I don't know what documents you are storing in Rethink. But something like this:
var thinky = require('thinky')();
var type = thinky.type;
// Create a model
var Urls = thinky.createModel("urls", {
id: String,
expires_at: Date
// another fields if needed
});
2) Query:
Don't know actual syntaxes for filter in Thinky, but somehting like this:
Urls.filter(function(url) {
return url("expires_at").date().eq(r.now().date())
.and(url("expires_at").hours().eq(r.now().hours().sub(1)))
}).then(function(result) {
// result is an array of instances of `Urls `
});
Related
I have this query that works
async find(ctx) {
let { _start, _limit } = ctx.request.query;
console.log(ctx.request.query)
_limit ? 0 : (_limit = 10);
const entities = await strapi.services["course-series"].find({});
return entities.map((entity) => {
// Do I sort them here or in the url query (and how)
entity.courses = entity.courses.slice(_start, _limit);
return sanitizeEntity(entity, { model: strapi.models["course-series"] });
});
}
The idea is that I can load 10 courses from each series at first and then get the next 10...
I just realized that the first 10 I am getting are not the recent ones.
As I commented // Do I sort them here or in the url query (and how)
What version of Strapi do you use?
What does this line do strapi.services["course-series"].find({})? How did you build this find method in the service? What does it do? Does it accept params?
Personally I'd do something like that (assuming you're working with Strapi version > 4:
const entities = await strapi.entityService.findMany('api::course-series.course-series', {
fields: [/* list the course-series fields you want to populate */],
populate: {
courses: {
fields: [/* list the course fields you want to populate */],
sort: 'createdAt:desc', // You can use id, publishedAt or updatedAt here, depends on your sorting prefrences
offset: _start,
limit: _limit // I must admit I haven't tested `offset` and `limit` on the populated related field
}
}
})
// ...the rest of your code, if needed
Read more about Entity Service API here.
Doing it the way you did it, you will always first retrieve the full list of courses for each course-series, and then run costly operations like mapping (the lesser of 2 evils) and above all sorting.
I have an GraphQL api implemented using HotChocolate 11. The schema changed recently and I would like to use our stitching layer to keep it the same for clients.
I have an mutation that looked like this:
type Mutation {
generate(apertures: [ApertureInput!]! templates: [TemplateInput!]!): [GeneratedApertures!]!
}
I had to add one more argument, also we added a query to get the additional data
type Mutation {
generate(apertures: [ApertureInput!]! templates: [TemplateInput!]! algorithm: AlgorithmInput!): [GeneratedApertures!]!
}
type Query {
standardAlgorithm: StandardAlgorithm
}
type StandardAlgorithm {
shrink: Int!
}
What I'm trying to do is to use our stitching layer to add the old signature of the mutation and call a remote schema in the resolver to get the additional data and pass it to the new mutation.
I have renamed the new signature on the stitch and created a mutation that looks like the old one:
extend type Mutation {
product_generate(apertures: [ApertureInput!]! templates: [TemplateInput!]! algorithm: AlgorithmInput!): GeneratedApertures!
#source(name: "generate" schema: "productdefinition")
#delegate(schema: "productdefinition")
generate(apertures: [ApertureInput!]! templates: [TemplateInput!]!): GeneratedApertures!
}
But I am lost using the stitching context to build the sub queries.
public class GenerationMutationTypeExtension : ObjectTypeExtension
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name("Mutation");
descriptor.Field("generate")
.Resolve(async ctx => {
var context = ctx.Service<IStitchingContext>();
var executor = context.GetRemoteRequestExecutor("productdefinition");
var request =
QueryRequestBuilder.New()
.SetQuery("{ standardAlgorithm { shrink } }")
.SetServices(executor.Services)
.Create();
var result = (QueryResult)await executor.ExecuteAsync(request);
var template = result.Data?["standardTemplate"];
if (template is NullValueNode || template is null) throw new GraphQLRequestException("Missing configuration!!!");
var shrink = (string)((IValueNode)((Dictionary<string, object>)template)["shrinkPercent"]).Value;
var apertures = ctx.ArgumentLiteral<IValueNode>("apertures");
var templates = ctx.ArgumentLiteral<IValueNode>("templates");
var selection = ctx.Selection.SyntaxNode.SelectionSet;
var query =
$"{{ product_generateDeposits(apertures: {apertures} templates: {templates} algorithm: {{ standardAlgorithm: {{ shrink: {shrink} }} }}) {selection} }}";
request =
QueryRequestBuilder.New()
.SetQuery(query)
.SetServices(executor.Services)
.Create();
result = (QueryResult)await executor.ExecuteAsync(request);
return result;
});
}
}
The first query for the shrink is working fine, I get the data. But I struggle with putting the other mutation together. Is there maybe a better way how to achieve this? Documentation is very vague when it comes to stitching.
I am fairly new to Apollo and Graphql and I quite don't know what I am doing wrong. I will try to explain my problem with some simplified code but if I am missing some information please let me know and I will update it.
I have an Apollo client instance consuming an external (Directus CMS) graphql API not modifiable by me.
The thing is I am querying a paginated (infinite scroll) of posts with offset and limit variables and the data returned is correct. I am using the following typePolicy in order to merge results arrays in my inMemoryCache. This code is from an example in the Apollo Docs:
posts {
const merged = existing ? existing.slice(0) : [];
const postIdToIndex = Object.create(null);
if (existing) {
existing.forEach((post, index) => {
postIdToIndex[readField("id", post)] = index;
});
}
incoming.forEach((post) => {
const id = readField("id", post);
const index = postIdToIndex[id];
if (typeof index === "number") {
// Merge the new post data with the existing post data.
merged[index] = mergeObjects(merged[index], post);
} else {
// First time we've seen this post in this array.
postIdToIndex[id] = merged.length;
merged.push(post);
}
});
return merged;
}
and this is a simplified version of my query:
query($offset: Int $limit: Int) {
posts(limit: $limit offset: $offset) {
id
name
}
}
With this merge function and query I get my pagination right and everything loads correctly. But when I try to query a single instance of post that queries also additional fields from it with the following query:
query($offset: Int $limit: Int $post_id: Int) {
posts(filter:{id:{_eq: $post_id}}) {
id
name
other_data
}
}
This returns undefined constantly when using useQuery() although i can see that is coming through my merge funtion and merging objects with the mergeObjects() function. If I use a fetchPolicy of no-cache in this query, the data returns correctly so it has something to do with the cache.
I hope someone can lead me in the right direction so I can fix this problem.
Thank you everyone in advance!!
In the code following this description, I am trying to find and remove all these bad ListConfig objects that didn't have a group object set. It is correctly finding them, however it does not remove them. Is there something I am missing in the following code?
var Groups = [];
function queryForGroups(callback) {
var Group = Parse.Object.extend("Group");
var query = new Parse.Query(Group);
query.limit(1000);
query.find().then(function(result) {
Groups = result;
callback();
});
};
function removeConfigs(){
var Config = Parse.Object.extend("ListConfig");
var query = new Parse.Query(Config);
query.limit(10000);
query.notContainedIn("group", Groups);
query.find().then(function(configs){
return Parse.Object.destroyAll(configs, {useMasterKey:true});
});
}
function removeBadConfigs() {
queryForGroups(function() {
removeConfigs();
});
};
removeBadConfigs();
The code could be a little cleaner with respect to mixing promises, callbacks and an unnecessary global. Beyond that, it looks like it should work as long as your data model supports it. Specifically, your ListConfig object must have a "group" property, and it must have a Parse.Object value set for that property. The most common error I've seen is something like this:
var myGroup = // a parse object of type Group
myListConfig.set("group", myGroup.id); // WRONG
myListConfig.set("group", myGroup); // RIGHT
Assuming you've got that right, then it's mysterious why you're not seeing some deletes, but here's the code cleaned up with promises...
function queryForGroups() {
let query = new Parse.Query("Group")
query.limit(1000);
return query.find();
};
function removeConfigsWithGroups(groups){
let query = new Parse.Query("Config");
query.notContainedIn("group", groups);
return query.find().then(function(configs){
return Parse.Object.destroyAll(configs, {useMasterKey:true});
});
}
function removeBadConfigs() {
return queryForGroups(function(groups) {
return removeConfigsWithGroups(groups);
});
};
removeBadConfigs();
I figured it out. I removed "useMasterKey: true" because 1) it isn't needed for objects not with elevated privileges and 2) I was not running it in Cloud Code.
I am working with Angular Meteor and am having an issue with my objects/arrays. I have this code:
angular.module("learn").controller("CurriculumDetailController", ['$scope', '$stateParams', '$meteor',
function($scope, $stateParams, $meteor){
$scope.curriculum = $meteor.object(CurriculumList, $stateParams.curriculumId);
$scope.resources = _.map($scope.curriculum.resources, function(obj) {
return ResourceList.findOne({_id:obj._id})
});
console.log($scope.resources)
}]);
I am attempting to iterate over 'resources', which is a nested array in the curriculum object, look up each value in the 'ResourceList' collection, and return the new array in the scope.
Problem is, sometimes it works, sometimes it doesnt. When I load up the page and access it through a UI-router link. I get the array as expected. But if the page is refreshed, $scope.resources is an empty array.
My thought is there is something going on with asynchronous calls but have not been able for find a solution. I still have the autopublish package installed. Any help would be appreciated.
What you're going to do is return a cursor containing all the information you want, then you can work with $meteor.object on the client side if you like. Normally, publishComposite would look something like this: (I don't know what your curriculum.resources looks like)
Use this method if the curriculum.resources has only ONE id:
// this takes the place of the publish method
Meteor.publishComposite('curriculum', function(id) {
return {
find: function() {
// Here you are getting the CurriculumList based on the id, or whatever you want
return CurriculumList.find({_id: id});
},
children: [
{
find: function(curr) {
// (curr) will be each of the CurriculumList's found from the parent query
// Normally you would do something like this:
return ResourceList.find(_id: curr.resources[0]._id);
}
}
]
}
})
This method if you have multiple resources:
However, since it looks like your curriculum is going to have a resources list with one or many objects with id's then we need to build the query before returning anything. Try something like:
// well use a function so we can send in an _id
Meteor.publishComposite('curriculum', function(id){
// we'll build our query before returning it.
var query = {
find: function() {
return CurriculumList.find({_id: id});
}
};
// now we'll fetch the curriculum so we can access the resources list
var curr = CurriculumList.find({_id: id}).fetch();
// this will pluck the ids from the resources and place them into an array
var rList = _.pluck(curr.resources, '_id');
// here we'll iterate over the resource ids and place a "find" object into the query.children array.
query.children = [];
_.each(rList, function(id) {
var childObj = {
find: function() {
return ResourceList.find({_id: id});
}
};
query.children.push(childObj)
})
return query;
});
So what should happen here (I didn't test) is with one publish function you will be getting the Curriculum you want, plus all of it's resourceslist children.
Now you will have access to these on the client side.
$scope.curriculum = $meteor.object(CurriculumList, $stateParams.curriculumId);
// collection if more than one, object if only one.
$scope.resources = $meteor.collection(ResoursesList, false);
This was thrown together somewhat quickly so I apologize if it doesn't work straight off, any trouble I'll help you fix.