Get raw parameters from react router - react-hooks

Is there any way to get the raw (without URL decoding) parameters from the react router V6.3 without making my own windows.location.href parser?
Example:
path: /companies/Samsung%2CInc,Lenovo%2CInc
const params = useParams();
const companies = params.companies?.split(',');
Expected:
[
'Samsung%2CInc',
'Lenovo%2CInc',
]
Getting:
[
'Samsung',
'Inc',
'Lenovo',
'Inc',
]
Any recommendations here?
PS. React Router does URL Decode, which is what I want to avoid. I found related issue on lib's issues board.

Apparently it is not possible at this moment. The URL decoding is coming from the matching part, which is a way deeper than useParams method.
I created a workaround gist that uses already parsed params and obtaining their RAW (URL encoded) version from the location.pathname
It works for my case, but I'm sure it could be optimized.

Related

Ruby YouTube Data API v3 insert caption always returns error

I am trying to use the Ruby SDK to upload videos to YouTube automatically. Inserting a video, deleting a video, and setting the thumbnail for a video works fine, but for some reason trying to add captions results in an invalid metadata client error regardless of the parameters I use.
I wrote code based on the documentation and code samples in other languages (I can't find any examples of doing this in Ruby with the current gem). I am using the google-apis-youtube_v3 gem, version 0.22.0.
Here is the relevant part of my code (assuming I have uploaded a video with id 'XYZ123'):
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'google-apis-youtube_v3'
def authorize [... auth code omitted ...] end
def get_service
service = Google::Apis::YoutubeV3::YouTubeService.new
service.key = API_KEY
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
service
end
body = {
"snippet": {
"videoId": 'XYZ123',
"language": 'en',
"name": 'English'
}
}
s = get_service
s.insert_caption('snippet', body, upload_source: '/path/to/my-captions.vtt')
I have tried many different combinations, but the result is always the same:
Google::Apis::ClientError: invalidMetadata: The request contains invalid metadata values, which prevent the track from being created. Confirm that the request specifies valid values for the snippet.language, snippet.name, and snippet.videoId properties. The snippet.isDraft property can also be included, but it is not required. status_code: 400
It seems that there really is not much choice for the language and video ID values, and there is nothing remarkable about naming the captions as "English". I am really at a loss as to what could be wrong with the values I am passing in.
Incidentally, I get exactly the same response even if I just pass in nil as the body.
I looked at the OVERVIEW.md file included with the google-apis-youtube_v3 gem, and it referred to the Google simple REST client Usage Guide, which in turn mentions that most object properties do not use camel case (which is what the underlying JSON representation uses). Instead, in most cases properties must be sent using Ruby's "snake_case" convention.
Thus it turns out that the snippet should specify video_id and not videoId.
That seems to have let the request go through, so this resolves this issue.
The response I'm getting now has a status of "failed" and a failure reason of "processingFailed", but that may be the subject of another question if I can't figure it out.

Using `createMockClient` for testing non react code?

I have mixed application that uses Apollo for both React and non-react code.
However, I can’t find documentation or code examples around testing non-react code with the apollo client,not using MockedProvider. I did, however, notice that apollo exports a mock client from the testing directory.
import { createMockClient } from '#apollo/client/testing';
I haven’t found any documentation about this API and am wondering if it’s intended to be used publicly and, if not, what the supported approach is for this.
The reason I need this is simple: When using Next.js’ SSR and/or SSG features data fetching and actual data rendering are split into separate functions.
So the fetching code is not using React, but Node.js to fetch data.
Therefore I use apolloClient.query to fetch the data I need.
When trying to wrap a react component around that fetching code in a test an wrap MockedProvider around that the apolloClient’s query method always returns undefined for mocked queries - so it seems this only works for the useQuery hook?
Do you have any idea how to mock the client in non-react code?
Thank you for your support in advance. If you need any further information from me feel free to ask.
Regards,
Horstcredible
I was in a similar position where I wanted to use a MockedProvider and mock the client class, rather than use useQuery as documented here: https://www.apollographql.com/docs/react/development-testing/testing/
Though it doesn't seem to be documented, createMockClient from '#apollo/client/testing' can be passed the same mocks as MockedProvider to mock without useQuery. These examples assume you have a MockedProvider:
export const mockGetAssetById = async (id: Number): Promise<any> => {
const client = createMockClient(mocks, GetAsset)
const data = await client.query({
query: GetAsset,
variables: id,
})
return data
}
Accomplishes the same as:
const { data } = useQuery(
GetAsset,
{ variables: { id } }
)

LiveQuery does not work, if there is no ParseConnectivityProvider provided

Racking my brains over this.
I cannot get past this issue, my code is producing this error:
LiveQuery does not work, if there is no ParseConnectivityProvider provided.
I tried playing around with the liveQueryURL and no luck. The flutter docs have no concrete example on how to implement this url from the server. I assume from the javaScript video and docs that it's my custom subdomain I created such as customdomain.b4a.io which makes the final url 'wss://customdomain.b4a.io'.
I looked into "connectivityProvider:" arg for the Parse().initialize but found nothing concrete on implementing this.
This is a dart demo project only. Any help or ideas much appreciated!
EDIT: This post does not solve my problem at all. It's also very old.
Is it possible this isn't working because this is a dart program rather than flutter? Wouldn't imagine this being the case...
Code:
import 'package:parse_server_sdk/parse_server_sdk.dart';
Future<void> main(List<String> arguments) async {
final keyApplicationId = 'XXX';
final keyClientKey = 'XXX';
final keyParseServerUrl = 'https://parseapi.back4app.com';
final liveQueryURL = 'wss://XXX.b4a.io';
await Parse().initialize(
keyApplicationId,
keyParseServerUrl,
clientKey: keyClientKey,
liveQueryUrl: liveQueryURL,
autoSendSessionId: true,
debug: true,
);
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query = QueryBuilder<ParseObject>(ParseObject('Color'));
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.create, (value) {
print('Object: ' + value['color']);
print((value as ParseObject).get('color'));
});
}
From https://github.com/parse-community/Parse-SDK-Flutter/issues/543#issuecomment-912783019
please provide a custom ParseConnectivityProvider (connectivityProvider in Parse().initialize).
In case you can assume your device has always internet access, the implementation should be as simple as this:
class CustomParseConnectivityProvider extends ParseConnectivityProvider{
Future<ParseConnectivityResult> checkConnectivity() => ParseConnectivityResult.wifi;
Stream<ParseConnectivityResult> get connectivityStream => Stream<ParseConnectivityResult>.empty();
}
(Not tested and typed on a smartphone.)
Unfortunately parse live query in flutter dose not work with https server url. I faced this problem before and it mades me crazy! What I did was in the backend side of parse server, provide both http and https servers. And In client side in flutter just connect to the http server for live queries!
And that works fine 😉

Suppress GraphQL: Syntax Error in VS Code when using template string

FYI: There are a ton of other posts concerning GraphQL Syntax Error in VS Code. I read many of them, but did not find anything relevant to this. My apologies if I missed it in the similar questions.
Environment:
VS Code v.1.51.1
Windows 10 x64 19041
https://github.com/apollographql/apollo-tooling v.1.17.0
React Typescript Application
I have a component that uses the useQuery hook. The query is retrieved from another query and comes in via a variable typed as string In order for the useQuery to correctly use the graphql query, it has first has to be made into a DocumentNode for which I use gql from graphql-tag npm package. The resulting code snippet looks like:
...
const PREPARED_QUERY = useMemo(() => gql`${query}`, [query])
const data = useQuery(PREPARED_QUERY, queryOptions)
...
This is working code, but the Apollo GraphQL extension throws a warning on this line:
Syntax Error: Unexpected <EOF>.GraphQL: Syntax
I understand this is because it is checking the query string to ensure that it is properly formatted and it does not understand the template string "hack".
Questions:
Can this be silences with some form of ignore comment?
If not, Is there any way to form this to make this template string pass the syntax check?
Looks like a known issue with the vscode extension - without a known solution :) https://github.com/graphql/vscode-graphql/issues/137 .
Workaround
Since gql is just a function, you can call it directly, so that the extension won't try to parse it and stop complaining.
gql(query)
Explanation on why it works
If we take a look at tagged templates docs, we'll see that it's a regular function that takes the array of static string pieces as the first argument, and interpolated expressions as the remaining arguments.
So when we do
gql`some content`
it translates to the following function call:
gql(["some content"]) // a single argument, because there is no interpolations here
Also this gql function has special code inside that allows to pass a plain string as the first arg (probably to support old JS where no template tags existed)

elastic APM and NestJS does not differentiate graphql queries

I am adding the elastic-apm-node package to our nestjs backend. I am using the graphql feature of nestjs. Because of this, all requests are merged together as /graphql in elastic.
Is this how it is supposed to be? I imagined that since apollo-server-express is supported by elastic-apm-node, which is also used by nestjs, it should be displaying it better. Am I missing something?
UPDATE
The graphql feature is set up using the docs for nestjs: https://docs.nestjs.com/graphql/quick-start it is basically their recommended setup I am using.
It's hard to say without knowing exactly how you're using NestJS and GraphQL together, and without knowing which parts of Apollo Server that NestJS itself uses. Seeing a small sample of what I am using the graphql feature of nestjs means would be useful.
Here's a few datapoints that might help you narrow things down. Also, opening an issue in the Agent repository or a question in their forums might get more of the right eyes on this.
The Elastic APM instrumentation for Apollo Server works by wrapping the runHttpQuery function of the apollo-server-core module, and marking the transaction with trans._graphqlRoute.
When the agent sees this _graphqlRoute property, it runs some code that will set a default name for the transaction
if (trans._graphqlRoute) {
var name = queries.length > 0 ? queries.join(', ') : 'Unknown GraphQL query'
if (trans.req) var path = getPathFromRequest(trans.req, true)
var defaultName = name
defaultName = path ? defaultName + ' (' + path + ')' : defaultName
defaultName = operationName ? operationName + ' ' + defaultName : defaultName
trans.setDefaultName(defaultName)
trans.type = 'graphql'
}
In your application, either the _graphqlRoute property isn't getting set, or the renaming code above is doing something weird, or something about NestJS comes along and renames the transaction after it's been named with the above code.
Knowing more specifically what you're doing would help folks narrow in on your problems.

Resources