Following Meteor docs on how to use the import directory structure, Example directory layout.
//-------------- publication.js`
import {Vehicles} from '../vehicles.js';
Meteor.publish('vehicles', function () {
return Vehicles.find();
});
//-------------- carClass.jsx
import './vehicles/server/publications.js';
const composer = (props, onData) => {
const subscription = Meteor.subscribe('vehicles');
if (subscription.ready()) {
const vehicle = Vehicles.findOne({name: 'jack'});
onData(null, { vehicle });
}
};
Does the publish method need to be exported?
Error in browser console saying:
Uncaught Error: Cannot find module './vehicles/server/publications.js'
How can this error be fixed? Thanks
Meteor publications are server-only code, so you can't import that script in carClass.jsx.
You should have some file like {app root}/server/main.js. You import your publications here to make them available for client scripts to subscribe to. It's important that this file isn't inside of the /imports folder, so that it is eagerly loaded when the server starts.
The problem is that the path ./vehicles/server/publications.js is not reachable from the carClass.jsx file. You should reference it by ./server/publications.js
Related
while working on the local host, api and the posts.jaon file also works fine. was able to perform CRUD.But after I deploy it to vercel, the api does not loads.
error in the log is something like this:
[GET] /api/insta 11:39:32:83 [Error: ENOENT: no such file or directory, open './posts.json'] { errno: -2, code: 'ENOENT', syscall: 'open', path: './posts.json' }
expecting a json response in the browser when I hit the api.
the json file is in the pages/api folder of next app.
I tried moving the json file outside pages at the top level of the folder strecture, and changing the path inside the fs("file.json",....). but nothing worked
This article from Vercel might help you:
How to Load Data from a File in Next.js
Here is an excerpt:
import path from 'path';
import { promises as fs } from 'fs';
export default async function handler(req, res) {
const jsonDirectory = path.join(process.cwd(), 'json');
const fileContents = await fs.readFile(jsonDirectory + '/data.json', 'utf8');
res.status(200).json(fileContents);
}
You would then have a folder named json where all the data is saved. That is declared in line 4. If you want to rename it, it is of course possible.
I'm using EJS to build email templates. The problem I'm having is I don't know what is the best location to keep these EJS files and any other file import for production (could be even a zip file in future).
Currently I'm keeping email templates under src/emails folder (next root is src). I performed a test with the following and everything works fine :
import type { NextApiRequest, NextApiResponse } from 'next';
import path from 'path';
const ejs = require('ejs')
type Data = {
name: string;
};
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const basePath = path.join(process.cwd(), 'src/emails');
ejs.renderFile(basePath + '/userVerification.ejs', { verifyURL: 'testurl' }, (err: {}, data: any) => {
console.log(data);
res.status(200).end('test');
});
}
But I noticed NextJS is getting the file from src folder which won't be available on server. I thought maybe I can put them into src/public folder since it'll be exported but I couldn't make sure.
My question is where is the best location for keeping these files?
After performing a few tests, I noticed that api can actually access to anything within project folder. Only public folder content can be accessed publicly by URL. That being said folder location for custom files can be anywhere.
.next
public
server_files *(all files can be imported by API)*
--ejs (templates email templates)
--pdf (generated invoice etc.)
--zip
src
--components
--pages
My Main goal is to create an Electron App (Windows) that locally stores data in an SQLite Database. And because of type safety I choose to use the Prisma framework instead of other SQLite Frameworks.
I took this Electron Sample Project and now try to include Prisma. Depending on what I try different problems do arrise.
1. PrismaClient is unable to be run in the Browser
I executed npx prisma generate and then try to execute this function via a button:
import { PrismaClient } from '#prisma/client';
onSqlTestAction(): void {
const prisma = new PrismaClient();
const newTestObject = prisma.testTable.create(
{
data: {
value: "TestValue"
}
}
);
}
When executing this in Electron I get this:
core.js:6456 ERROR Error: PrismaClient is unable to be run in the browser.
In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues
at new PrismaClient (index-browser.js:93)
at HomeComponent.onSqlTestAction (home.component.ts:19)
at HomeComponent_Template_button_click_7_listener (template.html:7)
at executeListenerWithErrorHandling (core.js:15281)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:15319)
at HTMLButtonElement.<anonymous> (platform-browser.js:568)
at ZoneDelegate.invokeTask (zone.js:406)
at Object.onInvokeTask (core.js:28666)
at ZoneDelegate.invokeTask (zone.js:405)
at Zone.runTask (zone.js:178)
It somehow seems logical that Prisma cannot run in a browser. But I actually build a native app - with Electron that embeds a Browser. It seems to be a loophole.
2. BREAKING CHANGE: webpack < 5 used to include polyfills
So i found this Question: How to use Prisma with Electron
Seemed to be exactly what I looked for. But the error message is different (Debian binaries were not found).
The solution provided is to generate the prisma artifacts into the src folder instead of node_modules - and this leads to 19 polyfills errors. One for example:
./src/database/generated/index.js:20:11-26 - Error: Module not found: Error: Can't resolve 'path' in '[PATH_TO_MY_PROJECT]\src\database\generated'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
And this repeats with 18 other modules. Since the error message to begin with was different I also doubt that this is the way to go.
I finally figured this out. What I needed to understand was, that all Electron apps consist of 2 parts: The Frontend Webapp (running in embedded Chromium) and a Node backend server. Those 2 parts are called IPC Main and IPC Renderer and they can communicate with each other. And since Prisma can only run on the main process which is the backend I had to send my SQL actions to the Electron backend and execute them there.
My minimal example
In the frontend (I use Angular)
// This refers to the node_modules folder of the Electron Backend, the folder where the main.ts file is located.
// I just use this import so that I can use the prisma generated classes for type safety.
import { TestTable } from '../../../app/node_modules/.prisma/client';
// Button action
onSqlTestAction(): void {
this.electronService.ipcRenderer.invoke("prisma-channel", 'Test input').then((value) => {
const testObject: TestTable = JSON.parse(value);
console.log(testObject);
});
The sample project I used already had this service to provide the IPC Renderer:
#Injectable({
providedIn: 'root'
})
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
webFrame: typeof webFrame;
remote: typeof remote;
childProcess: typeof childProcess;
fs: typeof fs;
get isElectron(): boolean {
return !!(window && window.process && window.process.type);
}
constructor() {
// Conditional imports
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
// If you want to use a NodeJS 3rd party deps in Renderer process (like #electron/remote),
// it must be declared in dependencies of both package.json (in root and app folders)
// If you want to use remote object in renderer process, please set enableRemoteModule to true in main.ts
this.remote = window.require('#electron/remote');
}
}
And then in the Electron backend I first added "#prisma/client": "^3.0.1" to the package.json (for the Electron backend not the frontend). Then I added to the main.ts this function to handle the requests from the renderer:
// main.ts
ipcMain.handle("prisma-channel", async (event, args) => {
const prisma = new PrismaClient();
await prisma.testTable.create(
{
data: {
value: args
}
}
);
const readValue = await prisma.testTable.findMany();
return JSON.stringify(readValue);
})
This way of simply adding the IPC Main handler in the main.ts file of course is a big code smell but usefull as minimal example. I think I will move on with the achitecture concept presented in this article.
Good day developers! I'm working with Meteor.js it's my 1st expirience
I created collection in file
// ./dbs/messages.js
import { Mongo } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
export const Messages = new Mongo.Collection('messages');
and use it in api point with calling Messages.insert like that
// server/mail.js
import Messages from './dbs/messages.js';
Meteor.methods({
'message.post'(messageText, location){
Messages.insert({
messageText: messageText,
location: location
});
}
})
But when I call 'message.post' I get an error
Exception while invoking method 'message.post' TypeError
Messages.insert is not a function
BUT, when I comment collection import and declare it in server/main.js like that
// import Messages from './dbs/messages.js';
const Messages = new Mongo.Collection('messages');
Meteor.methods({
'message.post'(messageText, location){
Messages.insert({
messageText: messageText,
location: location
});
}
});
In this case my Messages.insert works properly.
Who has experience with Meteor - can you explain me what is the reason?
Thanks!
Also I have removed autopublish and insecure packages
As #MasterAM and #Ankur Soni said you need to import Messages using brackets import { Messages } from './dbs/messages.js';
The only way to import without brackets is by defining Messages and then exporting it like so export default Messages;
I initiate my collections in a "common" space. I feel what you did is actually right. You either declare the collection twice, once on the client side and once on the server side or do it only once in a common folder. I see in many documentations that the popular place to keep these declarations is the /imports/api ... which is common to both server and client.
Rgs,
Paul
How do I correctly import my collection definition?
I get this error message when as a result of trying to import
I externalized my collection definition FROM the main myMeteorApp.js file:
(My directory structure looked like this:)
/myMeteorApp
/myMeteorApp.js
...TO the tasks.js file:
(My directory structure currently looks like this:)
/myMeteorApp
--/imports/api/tasks.js
The contents of tasks.js look like this:
import { Mongo } from "meteor/mongo";
const Images = new FS.Collection("images", {
stores: [new FS.Store.FileSystem("images", {path: "~/uploads"})]
});
const buyList = new Mongo.Collection("BuyList");
const WhoAreWe = new Mongo.Collection("whoDb");
const merchantReviews = new Mongo.Collection("MerchantReviews");
const Messages = new Meteor.Collection("messages", {transform: function (doc) { doc.buyListObj = buyList.find({sessionIDz: {$in: [doc.buyList]}}); return doc; }});
export { Images };
export { buyList };
export { WhoAreWe };
export { merchantReviews };
export { Messages };
I have packages babel-preset-es2015 and ecmascript installed, but these haven't helped.
Looking forward to your help...
Everything is the chat session we had indicates that your original app used Meteor 1.2, which did not support ES2015 modules. In addition, you did not import them correctly.
Here is a short checklist for import-related issues:
Make sure that your project is actually using Meteor v1.3+ (run meteor --version). Earlier versions did not support the modules feature.
Make sure that you have the ecmascript package installed (run meteor list or cat .meteor/packages | grep ecmascript from your project's root directory. If not, meteor add ecmascript. This is the package used for compiling ES2015.
Make sure that you are using it correctly. There are 2 types of exports:
default - import foo from 'imports/bar' goes with export default bar.
named - import { foo } from 'imports/bar' goes with export const foo = ..., etc.