How to queries in supabase realtime? - sql

Most of the blogs and stacks suggests below database for chat.
message_table
-id
-message
-conversationId
-sender
-receiverId
conversation_table
-id
-conversationId
Now message_table look like this.
So, for the chat screen I subscribe the message table.
final mySubscription = supabase
.from('message_table')
.on(SupabaseEventTypes.all, (payload) {
// Handle realtime payload
})
.subscribe();
if user1 and user2 are chatting, they will get all messages from this table.
So, how to filter this data with specified conversationId in supabase to stop receive the other message of other users and for reduce of bandwidth ?
And Is this database viable ?

You can add eq filter on your realtime listeners like this:
supabase-flutter v1.X
final subscription = supabase.channel('unique_channel').on(
RealtimeListenTypes.postgresChanges,
ChannelFilter(
event: '*',
schema: 'public',
table: 'message_table',
filter: 'conversationId=eq.conv12',
), (payload, [ref]) {
// handle realtime here
}).subscribe();
supabase-flutter v0.X
final subscription = supabase
.from('message_table:conversationId=eq.conv12')
.on(SupabaseEventTypes.all, (payload) {
// Handle realtime payload
})
.subscribe();
You can read more about this feature on the official Supabase documentation here!

Finds all rows whose column satisfies the filter.
var conversationId = yourvalue ;
final mySubscription = supabase
.from('message_table')
.select('message, conversationId, sender , receiverId')
.eq('conversationId', conversationId) // Correct
.on(SupabaseEventTypes.all, (payload) {
// Handle realtime payload
})
.subscribe();

Related

I want to get recipient_signing_uri from the Docusign API response but it returns null

Here is the code
public function send(Request $request): object
{
$apiClient = new ApiClient();
$apiClient->getOAuth()->setOAuthBasePath(env('DS_AUTH_SERVER'));
try {
$accessToken = $this->getToken($apiClient);
} catch (\Throwable $th) {
return back()->withError($th->getMessage())->withInput();
}
$userInfo = $apiClient->getUserInfo($accessToken);
$accountInfo = $userInfo[0]->getAccounts();
$apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));
$envelopeDefenition = $this->buildEnvelope($request);
try {
$envelopeApi = new EnvelopesApi($apiClient);
$result = $envelopeApi->createEnvelope($accountInfo[0]->getAccountId(), $envelopeDefenition);
dd($result);
} catch (\Throwable $th) {
return back()->withError($th->getMessage())->withInput();
}
return view('backend.response')->with('result', $result);
}
When I print $result variable it returns a response like this
container: array:8 [
"bulk_envelope_status" => null
"envelope_id" => "b634f8c5-96c5-4a18-947f-59418d8c4e03"
"error_details" => null
"recipient_signing_uri" => null
"recipient_signing_uri_error" => null
"status" => "sent"
"status_date_time" => "2023-02-16T07:24:39.1570000Z"
"uri" => "/envelopes/b634f8`your text`c5-96c5-4a18-947f-59418d8c4e03"
]
I want to get the value of recipient signing uri in response but in my case it returns null
How I can achieve this? Will anyone suggests?
createEnvelope creates the envelope. It does not give you an URL for an embedded recipient view (signing ceremony). In order to get that URL, you need to make an additional call to
EnvelopeViews:createRecipient/
See this page for more info.
Also
$apiClient->getConfig()->setHost($accountInfo[0]->getBaseUri() . env('DS_ESIGN_URI_SUFFIX'));
You are using the first entry in the UserInfo returned data's accountInfo array. That's not a good idea. Instead, look for the entry that is the user's default account.
Or if your application is designed to work with a specific eSign account, then make sure the user has access to that account.
It is very common for DocuSign customers to have access to more than one account.

Get roles by name in a 'guildMemberAdd' handler

Since member.guild.roles.get('roleName') no longer works. I'd like to know if there's an alternative to it.
message.guild.roles.cache.find(role => role.name == 'My Role Name') is not an option, since I don't have access to message object inside the 'guildMemberAdd' handler.
My code works fine using the role id, but I'd like to make it usable for other servers.
** updating my question
This is my code:
const role1 = 'the id number here'; ---> this one I'd like to be by name
const role2 = 'the id number here');
if (collected.first().emoji.name === '😎') {
member.roles.add(role1);
} if (collected.first().emoji.name === '🟩'){
member.roles.add(role2);
} else { return}
You can access the guild from GuildMember
client.on('guildMemberAdd', member => {
// member.guild.roles.cache.find(...) - Callback similar to Array#find()
// member.guild.roles.cache.get(...) - string id parameter only
});

Supabase, filter by column value of foreign key row

I am trying to figure out how to implement a query in supabase:
Schema
CREATE TABLE cars
(
id SERIAL PRIMARY KEY,
brand TEXT
);
CREATE TABLE stores
(
id SERIAL PRIMARY KEY,
car INT REFERENCES car(id),
name TEXT
);
I want to get all stores which carry the car of brand "x"
In Supabase I can filter like this:
let { data: stores } = await supabase
.from('stores')
.select("*")
.eq('name', 'Ford car shop')
// Returns
{
id: 123456,
car:"Ford",
name:"Ford car shop"
}
or join like this:
let { data: stores } = await supabase
.from('stores')
.select(`
*,
cars (
brand
)
`)
.eq('name', 'Ford car shop')
// Returns
{
id: 123456,
car:"Ford",
cars: {
id: 654321,
brand: "Ford"
}
name:"Ford car shop"
}
But how can I filter stores by the brand of the car they carry using the supabase sdk?
2022: This is now possible with supabase client. You can use the !inner() function.
let { data: stores } = await supabase
.from('stores')
.select('*, cars!inner(*)')
.eq('cars.brand', 'Ford')
Doc here: Filtering with inner joins
You can use the built in postgrest api supabase gives you to get this info. e.g:
/projects?select=*,clients!inner(*)&clients.id=eq.12
this isn't added to the supabase client yet.
the patch is shown here: https://github.com/PostgREST/postgrest/releases/tag/v9.0.0
Edit:
Supabase recently added this feature. The new accepted answer is below.
I did some more research and found out that this is currently not possible. However, it seems like it has been implemented and will make it into the next Supabase release.
An interim solution is using views and then querying those.
CREATE VIEW stores_expanded AS
SELECT
stores.id,
stores.name,
cars.brand
FROM
stores
LEFT JOIN cars
ON
stores.car = cars.id;
let { data: stores } = await supabase
.from('stores')
.select("*")
.eq('brand', 'x')

Why is POST request with pool.query only works intermittently when using :id in the middle of URL?

I wasn't quite sure how to phrase this question so feel free to make corrections to improve it as desired.
My goal is to make an HTTP POST that will create comments for a post and add the comment to the database comments table. I believe this necessitates doing an INSERT as well as a JOIN to add the specific POST id to the comment.
This is my first time including two requests in one query so I am unsure if this is correct. I had read about using a UNION but haven't been able to figure out the correct syntax as none of the examples included quotes '' around their requests.
My post route:
router.post(`/posts/:id/comments`, (request, response, next) => {
const { id } = request.params; // tried with and without brackets {}
const { comment_body } = request.body;
// Testing for correct params
console.log(id);
console.log(comment_body);
pool.query(
'INSERT INTO comments(comment_body) VALUES($1)',
[post_id, comment_body],
'SELECT * FROM comments JOIN posts ON posts.post_id = commments.post_id',
(err, res) => {
if (err) return next(err);
}
);
});
What is strange is that this worked twice then stopped working. There are two entries in the comments table but any further posts don't do anything. This only worked from the comments form and not yet in Postman
This worked in two separate tests. When using brackets around the id, the post was created in the table but no post_id was joined on this table:
const { id } = request.params;
If I didn't use the brackets, the post_id was created in the data table:
const id = request.params;
Here are my tables:
CREATE TABLE posts(
post_id SERIAL,
user_id INT,
post_body CHARACTER varying(20000)
);
CREATE TABLE comments(
id SERIAL,
post_id INT,
user_id INT,
comment_body CHARACTER varying(20000)
);
Originally I had the post_id for comments set as serial but figured if that is supposed to be joined from the posts.post_id, it would probably need to be INT.
Thanks much for any direction.
I managed to solve this with the following:
router.post(`/posts/:id/comments`, async (request, response, next) => {
try {
const { id } = request.params;
const { comment_body } = request.body;
await pool.query
('INSERT INTO comments(post_id, comment_body) VALUES($1, $2)',
[id, comment_body]);
} catch(error) {
console.log(error.message)
}
});
Rather than using the JOIN, I just included the posts ID parameter in the original INSERT and imported it that way. I had initially thought I had to do it as a join but couldn't get a second SQL request to work. Thanks to snakecharmerb for the idea.
I also added async/await.

NODE JS Passing characters in get request

I am using Node and Express with MSNODESQLV8 to write an API demo (my first) to get some rows from a remote SQL Server instance. My other get queries work fine when searching for an ID which is a number but I am unsure how to pass a value in the form of characters to a parameter in my query. Pretty sure req.params.id is not appropriate.
app.get("/productsname/:id", (req, res) => {
const productName = req.params.id;
const productsNameQuery = "SELECT * FROM Products WHERE ProductName = ?";
sql.query(connStr, productsNameQuery, [productName], (err, rows) => {
if (err) {
console.log(`Failed to get product by id ${req.params.id}. ${err}`);
res.sendStatus(500);
}else {
res.json(rows);
}
})
});
I want to take a product name (string?) in at the end of the url where it reads "id" and pass it as a value to the productName const. The end goal is to retrieve all rows from the SQL table where the product name is "processor" in the get url (http://localhost:2000/productname/proccesor). Perhaps I am passing the url incorrectly?
Apologies if this is really basic. I am very new to this.
Thanks in advance