FileError { kind: IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" }), path: "Some(\"assets/images/tiles/air.png\")" }' - file

Tell me if I need to provide more info, I am rather new here. Here is the code:
let mut image_paths = vec![];
let mut images = vec![];
let mut image_path = "assets/images/tiles/";
for img in glob(format!("{}*.png",image_path).as_str()).unwrap() {
match img {
Ok(path) =>{
image_paths.push(format!("{:?}",path.to_str()));
},
Err(e) => continue,
}
}
for i in &image_paths {
images.push(load_texture(i).await.unwrap());
}
But I get this error:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: FileError {
kind: IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" }),
path: "Some(\"assets/images/tiles/air.png\")" }', src/main.rs:71:43
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Which is really bizarre, because I can confirm that 'air.png' is in the 'tiles' folder, I have been able to load the image simply by doing load_texture(), but I don't understand why I cannot load it now.

Path::to_str returns an Option<&str>. You're applying debug formatting ({:?}) on that, then adding the result to image_paths. I'm pretty sure your file path isn't supposed to start with Some(.
When you work with paths in Rust, you generally want to use Path or PathBuf unless you need to display the path. Check to see if load_texture could receive a &Path or a PathBuf. If not, then you need to unwrap the Option or deal with the None in whatever way is appropriate for your situation.
image_paths.push(path.to_str().unwrap());
// or if you need a `String` instead of a `&str`:
image_paths.push(path.to_str().unwrap().to_string());

Related

useQuery with tRPC wont recieve my query input

I am new to tRPC and react-query. I've been working to test .query (BE) and useQuery (FE) and I tried to pass data from FE to BE. However, since TS is a static typing, I get compile error although the code is working (it's working smoothly if I change to JS).
Here's my BE
export const appRouter = trpc
.router()
.query("greet", {
input: z
.object({
name: z.string().nullish(),
})
.default({ name: "World" }),
resolve({ input }) {
return {
message: `Hello ${input.name?.toUpperCase()}!`,
};
},
})
and my FE is calling it by
const greet = trpc.useQuery(["greet", { name: "Maria" }]);
The compile error is on the { name: "Maria" } part.
It says "Type '{ name: string; }' is not assignable to type 'null | undefined'.ts(2322)". I don't know why the useQuery type definition
is like this. Which I think I can't pass any parameters at all(?)
Please help, I have no idea. Thanks for reading and answering my question :)
Try removing the .nullish part and adding a ':' after resolve like this:
export const appRouter = trpc
.router()
.query("greet", {
input: z
.object({
name: z.string().,
})
.default({ name: "World" }),
resolve: async ({ input }) => {
return {
message: `Hello ${input.name?.toUpperCase()}!`,
};
},
})
I am also quite new to trpc so i'm sorry if this doesn't help.
I just had a similar problem and been poking and prodding it for two days.
Turns out it goes away once you set strict to true in the tsconfig.json under compilerOptions
The fragility of the TypeScript tool-chain never ceases to amaze me.
A little bit of update, I have resolved this problem by moving to a new repo, lol.
I think the problem is possibly caused by
Possibility 1: The undefined createReactQueryHooks in the "trpc" so you need to specify const trpc = new createReactQueryHooks<AppRouter>(); with the AppRouter being the appRouter type you export from the BE. Don't do const trpc = new createReactQueryHooks(); with "any" type.
Possibility 2: Your javascript and typescript package overlaps, so the compiler might mistakenly detect the javascript one which most of them do not specify type.
Ran into this issue on VSCODE. Quitting VS code, and reopening the project solved this (it also then properly showed any underlying issues).

Is it possible to rewrite the route of a static .txt file in Next.js

I have a Next.js application which has a robots-staging.txt file in the root of the public folder. I'm looking to add this to the rewrites function in next.config. This is what I have
async rewrites() {
const rewriteList = [
{
source: '/robots-staging.txt',
destination: '/robots.txt',
},
];
return rewriteList;
},
My initial expectation was that when I hit localhost:3000/robots.txt this would serve the staging file, however it's not working. Am I missing something?
If I understood correctly that you want to proxy /robots.txt to /robots-staging.txt, you need to make the latter the destination and not the source.
Besides that, I've experienced the same issue, and I'm not sure if this is a bug or a feature, but I found that using absolute paths/URLs works as a workaround as relative paths seem to be interpreted as pages:
async rewrites() {
{
source: "/robots.txt",
destination:
process.env.NODE_ENV === "development"
? "http://localhost:3000/robots-staging.txt"
: "https://YOUR_URL/robots-staging.txt",
},
];
},

How can I access intl.formatMessage() in mobx store in reactJS app?

I have two JSON files with names 'en.json' and 'fr.json' which has all the translations.
en.json
{ "General.LearnMore": "Learn More" }
I have a mobx store (.ts file) and I want to access intl.formatMessage() in that class.
It is easier in functional components. I can use useIntl() hook but how can I do the same in a store file (non-component).
When I write the below code in store file:
const messages = defineMessages({
SMS: {
id: 'General.LearnMore',
},
});
const cache = createIntlCache();
const locale = localStorage.getItem('locale')!;
const intl = createIntl({ locale, messages: {} }, cache);
console.log(intl.formatMessage({ id: 'General.select' }));
console.log(intl.formatMessage({ id: messages.sms.id }));
It gives this error:
What I am missing and How can I fix this? Please help!
In createIntl you pass an empty object to messages so intl doesn't find the ids.
To fix, import the en.json:
import enMessages from '../path/to/en.json'
and pass it on cretaeIntl:
const intl = createIntl({ locale, messages: enMessages }, cache);
If you created the messages object with defineMessages just for the purpose of getting value from intl - you can delete it, it doesn't give access to the key-value files (createIntl doesn't automatically get the data of intlProvider, it needs full initialition with locale and messages)
If you want the messages to be updated every time the locale is switched so here a good example
Hope this will help!

TypeError: fs.existsSync is not a function

I'm trying to use Winston in React.js.
When creating the logger I get the error
TypeError: fs.existsSync is not a function
This is how I create it:
this.logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
I only saw questions about how to handle it in Node. How do I solve this issue with React?
fs is a nodejs library so you can't use it on browser side. Use winston-transport-browserconsole instead.
https://www.npmjs.com/package/winston-transport-browserconsole
It is easy to use and supports logging json objects:
example-
import * as winston from "winston";
import BrowserConsole from 'winston-transport-browserconsole';
const level = "debug";
winston.configure({
transports: [
new BrowserConsole(
{
format: winston.format.simple(),
level,
},
),
],
});
winston.debug("DEBUG ", {a: 1, b: "two"});
I had the same error that you have. Your vscode might have added a new module to your js file. Remove that module and your app should work just fine.
import { TRUE } from "node-sass"; or import { FALSE } from "node-sass";
just remove the above codes

Ionic 2 File Plugin usage examples

Does anyone have complete examples about how to use the Cordova Native File Plugin in a Ionic 2/Angular 2 project?
I installed this plugin but the documentation don't seems to make much sense to me due the fact it is fragmented and lacks of a complete example, including all needed imports.
For example, the following example don't shows where objects like LocalFileSystem or window came from.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
console.log('file system open: ' + fs.name);
fs.root.getFile("newPersistentFile.txt", { create: true, exclusive: false }, function (fileEntry) {
console.log("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
For example, I need to crate a property file. First I need to check if a file exists on app sandbox storage area, if don't exists I must create it. Then I must open the file write data and save it . How could I do that?
Ionic 2 comes with a Cordova file plugin wrapper:
http://ionicframework.com/docs/v2/native/file/.
The necessary file system paths (e.g. cordova.file.applicationDirectory) you can find here at the documentation of the original plugin:
https://github.com/apache/cordova-plugin-file#where-to-store-files. Note that not all platforms support the same storage paths.
I even managed to build a file browser with it. Use it like so:
import {Component} from '#angular/core';
import {File} from 'ionic-native';
...
File.listDir(cordova.file.applicationDirectory, 'mySubFolder/mySubSubFolder').then(
(files) => {
// do something
}
).catch(
(err) => {
// do something
}
);
Here is an example using IonicNative for an app I am working on where I want
to send an email with a csv file attachment.
import {EmailComposer} from '#ionic-native/email-composer';
import {File} from '#ionic-native/file';
class MyComponent {
constructor(private emailComposer: EmailComposer, private file: File) {
}
testEmail() {
this.file.writeFile(this.file.dataDirectory, 'test.csv', 'hello,world,', {replace: true})
.then(() => {
let email = {
to: 'email#email',
attachments: [
this.file.dataDirectory + 'test.csv'
],
subject: 'subject',
body: 'body text...',
isHtml: true
};
this.emailComposer.open(email);
})
.catch((err) => {
console.error(err);
});
}
}
This was tested with ionic 3.7.0 on IOS.

Resources