In meteor project, do I need to import {Meteor},{Mongo}, and{check} in this example? Why?
collections.js
// import {Mongo} from 'meteor/mongo' // ---- i have to import this?
Bookmarks = new Mongo.Collection('bookmarks')
methods.js
// import {check} from 'meteor/check' // ---- i have to import this?
import {Bookmarks} from "/imports/schema/bookmarks/index"
Meteor.methods({
'bookmark.add'({name, url}){
check(name,String) // ---------------
check(url,String)
const bookmarkId = Bookmarks.insert({name,url})
Meteor.isServer && console.log(`Id ${bookmarkId} inserted`)
},
'bookmark.remove'(_id){
check(_id,String)
const bookmark = Bookmarks.findOne({_id})
if (!bookmark){
Meteor.isServer && console.log('no such a bookmark!')
} else {
const removeBookmarkId = Bookmarks.remove({_id})
Meteor.isServer && console.log(`remove result ${removeBookmarkId?'success':'error'}`)
}
}
})
The short answer is yes. Meteor makes heavy use of the module system for imports and exports. You can read more about how Meteor modules works, and the reasons motivating the move to Meteor modules here.
Related
Im trying to create a portfolio site for myself using sanity on the backend. The site is working and the DB is set up and working using Sanity studio, but I cant get it to connect properly on the backend using Next.
Here is my connection file:
import { createClient } from "next-sanity";
import createImageUrlBuilder from "#sanity/image-url";
export const client = createClient({
projectId: "p079sml5",
dataset: "production",
apiVersion: "2023-01-31",
useCdn: false,
});
I'll be hiding a lot of this in env files but for the purposes of debugging I've left the info in.
And here is one of my endpoints:
import { NextApiRequest, NextApiResponse } from "next";
import { groq } from "next-sanity";
import { client } from "sanity";
import { Social } from "./typings";
const query = groq`
*[_type == "social"]
`;
type Data = {
socials: Social[];
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const socials: Social[] = await client.fetch(query);
res.status(200).json({ socials });
}
As per the title, when trying to make the call on http://localhost:3000/api/getSocials, I get the following error: error - TypeError: Cannot read properties of undefined (reading 'fetch')
at handler (webpack-internal:///(api)/./src/pages/api/getSocials.ts:15:70)
Fetch appears on the autofill, along with the other methods, so it would appear that its been imported "correctly". The error suggests that that its the client that is the issue but cant figure out why.
Thanks in advance
Ive tried, using my dev environment, with the associated project id etc but no joy.
UPDATE: Fixed, I just moved the client file into a different folder, and it worked
Follow this doc https://github.com/vercel/next.js/tree/canary/examples/cms-sanity
Or setup this repo in new folder and update it's config (/lib/config.js) file with your sanity details then check... previously it was worked for me.
I'd like to use composables inside composables, but it turned out, that composables lose reactivity.
Please, give me advice how to tackle this problem.
The desired behavior is beneath:
import {ref, computed} from "vue";
import useFirstStep from "components/draft/use/useFirstStep";
import useSecondStep from "components/draft/use/useSecondStep";
export default function useFifthStep() {
const {isValidFirstStep} = useFirstStep();
const {isValidSecondStep} = useSecondStep();
const isValidStep = computed(() => {
return isValidFirstStep.value &&
isValidSecondStep.value &&
});
return {isValidStep};
}
It's hard to say without seeing the example code from useFirstStep and useSecondStep, but I bet you have a ref inside export, but you should keep it outside, so that whenever you use this composable you would not initialize given ref.
So useFirstStep.js should look like:
const isValidFirstStep = ref(false)
export default function useFirstStep() {
// some logic to set isValidFirstStep
return {isValidFirstStep};
}
In Deno it is possible to version the dependencies in the import statement, and there's no package.json like with npm.
But how to managed it's URLs and versions in a single place?
I will have multiple files and dependencies that will be declared all over my system.
For example:
dateUtils.ts
import { parseDate } from 'https://deno.land/std#0.50.0/datetime/mod.ts';
const DEFAULT_MASK = "dd-mm-yyyy";
export function parse(date: string): Date {
return parseDate(date, DEFAULT_MASK);
};
service.ts
import { v4 } from "https://deno.land/std/uuid/mod.ts";
export function process(request: any) {
const { token } = request;
const isValid = v4.validate(token);
console.log(`Token validity: ${isValid}`)
};
app.ts
import { parse } from "./dateUtil.ts";
import * as service from "./service.ts";
const date = parse("20-05-2020");
console.log(date);
const request = {
token: "408d30e5-1e90-45e3-b299-6520feee6d76"
}
service.process(request)
To avoid typing https://deno.land/std/uuid/mod.ts everywhere you can use import maps
// import_map.json
{
"imports": {
"http/": "https://deno.land/std/http/"
}
}
// server.ts
import { serve } from "http/server.ts";
const body = new TextEncoder().encode("Hello World\n");
for await (const req of serve(":8000")) {
req.respond({ body });
}
deno run --importmap=import_map.json --allow-net server.ts
import maps are currently unstable, but you can use them behind --unstable flag.
Aside from that it's common to have a deps.ts file where you'll re-export all your dependencies.
// deps.ts
export * as path from "https://deno.land/std#0.51.0/path/mod.ts";
// other exports .. from
// some other file
import { path } from './deps.ts' // instead of "https://deno.land/std#0.51.0/path/mod.ts"
path.basename('/bar/test.txt');
In deno there is a convention for consolidating imports into deps.ts.
export { parseDate } from 'https://deno.land/std#0.50.0/datetime/mod.ts';
export { v4 } from "https://deno.land/std/uuid/mod.ts";
Exports can then be imported in other modules/scripts on your application:
import { v4 } from "./deps.ts";
import { parseDate } from './deps.ts';
const myUUID = v4.generate();
parseDate("20-05-2020", "dd-mm-yyyy")
When using this approach one should consider integrity checking & lock files:
// Add a new dependency to "src/deps.ts", used somewhere else.
export { xyz } from "https://unpkg.com/xyz-lib#v0.9.0/lib.ts";
# Create/update the lock file "lock.json".
deno cache --lock=lock.json --lock-write src/deps.ts
# Include it when committing to source control.
git add -u lock.json
git commit -m "feat: Add support for xyz using xyz-lib"
git push
I use jest to run some test on my Create React App with Firebase Web SDK coupled with FirebaseUI
Whenever I try to run some tests with --env=jsdom - I run into :
The current environment does not support the specified persistence type. seems related to Auth
Are there any known related issue/workaround ? the code seems to work/compile properly aside from the tests.
Google didn't help much
Here is the test, pretty basic.
HAd to add import "firebase/storage"; because of this : firebase.storage() is not a function in jest test cases
Thanks in advance
import React from "react";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "firebase/storage";
import {filterIngredientsToRemove} from "./shoppingList-reducer";
Enzyme.configure({adapter: new Adapter()});
describe("", () => {
let shoppingList;
let recipeId;
beforeEach(() => {
shoppingList = {
shoppingListItems: {
"1234": {ingredientId: 987, name: "patate", recipeId: 1234},
"2345": {ingredientId: 987, name: "patate", recipeId: 5432}
},
shoppingListRecipes: {
"1234": {portion: 3}
}
};
recipeId = 1234;
});
it("should filter out the shoppinglistItems with the provided recipeId", () => {
const result = filterIngredientsToRemove(recipeId, shoppingList.shoppingListItems);
expect(result).toEqual([{ingredientId: 987, name: "patate", recipeId: 1234}]);
});
});
Are you setting persistence in your firebase config? Persistence is not supported in the test environment, so you can do something like this to circumvent it:
firebase.auth().setPersistence(process.env.NODE_ENV === 'test'
? firebase.auth.Auth.Persistence.NONE
: firebase.auth.Auth.Persistence.LOCAL);
I ran into this issue too. The problem seems to come from the firebaseui constructor, specifically this line of code in my app:
new firebaseui.auth.AuthUI(this.firebase.auth())
What I did to solve it was initialize the ui object only when actually using it to sign on, not just as a static (typescript) variable. This let me run jest tests that didn't try to sign on just fine.
private static ui: firebaseui.auth.AuthUI | undefined
static startAuthOnElement (selectorToUse: string, onSignedIn: () => void) {
if (this.ui === undefined) this.ui = new firebaseui.auth.AuthUI(this.firebase.auth())
// more code
}
This way all the code that doesn't call startAuthOnElement never runs the firebaseui constructor. This lets me run my jest tests just fine and auth still works in the app.
I have a collection named LibraryItems which is available on both client and server side.
api/libraryitems/libraryitems.js
import { Mongo } from 'meteor/mongo';
const LibraryItems = new Mongo.Collection('libraryitems');
export default LibraryItems;
Instead of an if (Meteor.isServer) {..} publication in this same file, I would like to have a server folder with the specific publications:
api/libraryitems/server/publications.js
import LibraryItems from '../libraryitems';
import { Meteor } from 'meteor/meteor';
Meteor.publish('LibraryItems.pub.all', function () {
return LibraryItems.find({});
});
But somehow, against my expectations, this publication is not available...
update
This is my subscription code (meteor+reactjs):
./imports/ui/Library.js
import LibraryItems from '../api/libraryitems/libraryitems';
import { createContainer } from 'meteor/react-meteor-data';
...
export default createContainer(() => {
Meteor.subscribe('LibraryItems.pub.all');
var libraryitems = LibraryItems.find().fetch();
return {
libraryitems: libraryitems
}
}, Library);
You are exporting LibraryItems as a default export, that means when you import it you don't need curly brackets around it.
Change your import to:
import LibraryItems from '../libraryitems';
Also, clean up the publication code slightly:
return LibraryItems.find({});
EDIT
Now that you have posted your subscription code as requested, I see that you are subscribing to the publication with a different name.
Change to:
Meteor.subscribe('LibraryItems.all');
Hope that helps
I forgot to register the publications in mains.js:
import '../imports/api/libraryitems/server/publications';