Scenario
I'm trying to get all entities from an endpoint, the ones on draft mode, and the ones on published mode.
I know that if I want to post on draft mode, I have to post published_at on null on the body request.
If I do:
/posts?published_at_null=true
that returns an empty array.
Question
How can I do to return ALL the posts?
It is on the documentation
https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#publication-state
But quick answer, URL + '?_publicationState=preview'
https://forum.strapi.io/t/draft-and-posted-entities/3576/2
you will have to create a custom control that will fetch all the entries.you cannot fetch draft data using the existing restapi urls.
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
async findUnpublished(ctx) {
//getting all the existing articles, no meter if they have unpublished status
let result = await strapi.query('posts').find();
//sanitize them to hide all private fields
let articles = sanitizeEntity(result, {
model: strapi.models['posts'],
});
//return result to the /findUnpublished API
ctx.send(articles);
}
};
Related
I have a question regarding a small issue that I'm having. I've created a widget that will live on the Service Portal to allow an admin to Accept or Reject requests.
The data for the widget is pulling from the Approvals (approval_approver) table. Under my GlideRecord, I have a query that checks for the state as requested. (Ex. addQuery('state', 'requested'))
To narrow down the search, I tried entering addQuery('sys_id', current.sys_id). When I use this query, my script breaks and I get an error on the Service Portal end.
Here's a sample of the GlideRecord script I've written to Accept.
[//Accept Request
if(input && input.action=="acceptApproval") {
var inRec1 = new GlideRecord('sysapproval_approver');
inRec1.addQuery('state', 'requested');
//inRec1.get('sys_id', current.sys_id);
inRec1.query();
if(inRec1.next()) {
inRec1.setValue('state', 'Approved');
inRec1.setValue('approver', gs.getUserID());
gs.addInfoMessage("Accept Approval Processed");
inRec1.update();
}
}][1]
I've research the web, tried using $sp.getParameter() as a work-around and no change.
I would really appreciate any help or insight on what I can do different to get script to work and filter the right records.
If I understand your question correctly, you are asking how to get the sysId of the sysapproval_approver record from the client-side in a widget.
Unless you have defined current elsewhere in your server script, current is undefined. Secondly, $sp.getParameter() is used to retrieve URL parameters. So unless you've included the sysId as a URL parameter, that will not get you what you are looking for.
One pattern that I've used is to pass an object to the client after the initial query that gets the list of requests.
When you're ready to send input to the server from the client, you can add relevant information to the input object. See the simplified example below. For the sake of brevity, the code below does not include error handling.
// Client-side function
approveRequest = function(sysId) {
$scope.server.get({
action: "requestApproval",
sysId: sysId
})
.then(function(response) {
console.log("Request approved");
});
};
// Server-side
var requestGr = new GlideRecord();
requestGr.addQuery("SOME_QUERY");
requestGr.query(); // Retrieve initial list of requests to display in the template
data.requests = []; // Add array of requests to data object to be passed to the client via the controller
while(requestsGr.next()) {
data.requests.push({
"number": requestsGr.getValue("number");
"state" : requestsGr.getValue("state");
"sysId" : requestsGr.getValue("sys_id");
});
}
if(input && input.action=="acceptApproval") {
var sysapprovalGr = new GlideRecord('sysapproval_approver');
if(sysapprovalGr.get(input.sysId)) {
sysapprovalGr.setValue('state', 'Approved');
sysapprovalGr.setValue('approver', gs.getUserID());
sysapprovalGr.update();
gs.addInfoMessage("Accept Approval Processed");
}
...
We had some code that has been working for the past 10 months (since it was developed) and just stopped working this afternoon. It's a WebAPI code to send a channel message mentioning the bot and a user, which now is returning "Bad Request. Invalid request body was sent."
If the "Mentions" property is not provided, the call works, and the message is sent without the #mentions. So, I wonder if there was a breaking change in this API that's now expecting a different format for the "Mentions" property.
It's quite simple to reproduce by following the example code found in the Microsoft Graph documentation.
I'm posting here in the hope some fellow dev spots something obvious or is aware of an alternative way of using the API that it might stop complaining, as Microsoft takes forever to reply.
Here's the code we have that can lead me to discover the issue:
private async Task SendMentionToTheBotAsync(GraphServiceClient onBehalfOfClient, string userName, string teamId, string channelId)
{
var supportAgentUser = await onBehalfOfClient.Me.Request().GetAsync();
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = $"<at id=\"0\">{Configuration["BotName"]}</at>: This is the start of the conversation between {userName} and <at id=\"1\">{supportAgentUser.DisplayName}</at>."
},
Mentions = new List<ChatMessageMention>
{
new ChatMessageMention
{
Id = 0,
MentionText = Configuration["BotName"],
Mentioned = new IdentitySet
{
Application = new Identity
{
DisplayName = Configuration["BotName"],
Id = Configuration["BotAppId"],
AdditionalData = new Dictionary<string,object>
{
{
"applicationIdentityType", "bot"
}
}
}
}
},
new ChatMessageMention
{
Id = 1,
MentionText = supportAgentUser.DisplayName,
Mentioned = new IdentitySet
{
User = new Identity
{
DisplayName = supportAgentUser.DisplayName,
Id = supportAgentUser.Id,
AdditionalData = new Dictionary<string,object>
{
{
"userIdentityType", "aadUser"
}
}
}
}
}
}
};
await onBehalfOfClient.Teams[teamId].Channels[channelId].Messages
.Request()
.AddAsync(chatMessage);
}
Microsoft Support responded with :
"Thank you for contacting Microsoft Support.
I understand the issue is related to the post messages to Teams. Based on the screenshot, it seems you are using mention to a channel. It's possible that you are using key "conversationIdentityType#odata.type" in your request.
Could you please try to remove "conversationIdentityType#odata.type" key from the request body and try again. It should work. It is because deployment is on the way in the Asia region. Once it's 100% rolled out, this key WILL NOT be entertained in the request."
Removed the key and it worked for me.
Paulo,
Unfortunately i am not a programmer. I am using Graph calls in a Microsoft 365 Power Automate workflow. I have an app that i use to get the Authorisation Bearer token and then post to Teams messages using a graph HTTP action.
Here is the syntax of the HTTP ( purple items are variables if u r not familiar with Flow )
click to view image of Power Automate workflow HTTP action
I want to retrieve row count in Supabase.
I am guessing it would be something like this:
const { data, error } = await supabase
.from('cities')
.select('name', 'COUNT(*)')
Is this possible with Supabase?
For future visitors, we are working on this functionality with the PostgREST maintainer:
https://github.com/supabase/postgrest-js/issues/94
(I'm a maintainer)
This is now released:
const { data, count } = supabase
.from('countries')
.select('*', { count: 'exact', head: true })
If you want to return the results simultaneously, remove head:
const { data, count } = supabase
.from('countries')
.select('*', { count: 'exact' })
As a workaround, you could write a standard Postgres stored procedure or function that returns the count then call that via the SB client.
https://supabase.io/docs/client/rpc
It is currently not supported yet, but there is a WIP issue on Github that would bring this feature to Supabase.
The code below has not been implemented in Supabase yet, but it might look something like this:
const { data, error, count } = await supabase
.from('table')
.select('*')
.gt('id', 10)
.count()
Edit 7.19.2021
As kiwicopple has answered, this feature has been added to Supabase with a slightly different form from what I have above. View the accepted answer for more.
I'm extending a create controller for one of my models:
async create(ctx) {
let entity;
if (ctx.is('multipart')) {
const { data, files } = parseMultipartData(ctx);
entity = await strapi.services.complaint.create(data, { files });
} else {
entity = await strapi.services.complaint.create(ctx.request.body);
}
const sanitized = sanitizeEntity(entity, { model: strapi.models.complaint });
strapi.emitToAllUsers('complaint::created', sanitized);
return sanitized;
},
It works fine if I do the request from Postman for example, but is it possible to do the same if the user creates the new object from the Admin UI?
When I see the console from Strapi when I send the request from Postman:
debug POST /complaints (58 ms) 200
But, if I create a new object from the admin UI I see this instead:
debug POST /content-manager/explorer/application::complaint.complaint (1017 ms) 200
Any ideas? Is it even possible? I'm using latest Strapi version (v3)
Thanks
If you want to execute something from Admin UI, I think you might want to look at how to implement it in models using lifecycle hooks.
https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#models
From what I know, controller only called on API, while service are a set of reusable functions. Models are called both by API and Admin UI.
complaint/models/complaint.js
module.exports = {
lifecycles: {
afterCreate(result, data) {
strapi.emitToAllUsers('complaint::created', result);
}
}
};
You can also create a function in service and call it models lifecycle hooks.
const { data } = await this.$axios.get(`/articles?_sort=published:ASC&_limit=9`)
Is there a way to actually sort on date or do I need to write my own custom route?
If am to build my custom route, what kind of query should I be using?
const { data } = await this.$axios.get(`/articles?_sort=published:desc&_limit=9`)
You were sorting by asc not desc