gatsby-source-graphql and GraphQL Shopify Admin API error - javascript

The repo with this code can be found HERE
I’m working on sourcing and combining data from Shopify Storefront and GraphQL Admin APIs into Gatsby. For sourcing Storefront API I use gatsby-source-shopify, though I wasn’t able to find source plugin for Shopify Admin API and ended up using gatsby-source-graphql.
I have created a private Shopify app and granted all permissions and was able to fetch data using curl example from Shopify GraphQL Admin API documentation.
curl -X POST \
"https://shop-name.myshopify.com/admin/api/2019-04/graphql.json" \
-H "Content-Type: application/graphql" \
-H "X-Shopify-Access-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d '
{
shop {
name
}
}
'
Output:
{"data":{"shop":{"name":"Shop Name"}},"extensions":{"cost":{"requestedQueryCost":1,"actualQueryCost":1,"throttleStatus":{"maximumAvailable":1000.0,"currentlyAvailable":999,"restoreRate":50.0}}}}
Error message:
success open and validate gatsby-configs — 0.007 s
success load plugins — 0.345 s
success onPreInit — 0.005 s
success initialize cache — 0.015 s
success copy gatsby files — 0.068 s
success onPreBootstrap — 0.006 s
error Plugin gatsby-source-graphql returned an error
Error: Parse error on "operationName" (STRING) at [1, 2]
gatsby-source-shopify/sandbox starting to fetch data from Shopify
gatsby-source-shopify/sandbox fetched and processed productTypes: 287.590ms
gatsby-source-shopify/sandbox fetched and processed policies: 297.440ms
gatsby-source-shopify/sandbox fetched and processed blogs: 302.418ms
gatsby-source-shopify/sandbox fetched and processed articles: 344.917ms
gatsby-source-shopify/sandbox fetched and processed collections: 8603.841ms
gatsby-source-shopify/sandbox fetched and processed products: 20362.561ms
gatsby-source-shopify/sandbox finished fetching data from Shopify: 20369.525ms
warning The gatsby-source-graphql plugin has generated no Gatsby nodes. Do you need it?
success source and transform nodes — 21.169 s
warning Multiple node fields resolve to the same GraphQL field `ShopifyArticle.blog` - [`blog`, `blog___NODE`]. Gatsby will use `blog___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyCollection.products` - [`products`, `products___NODE`]. Gatsby will use `products___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.options` - [`options`, `options___NODE`]. Gatsby will use `options___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.variants` - [`variants`, `variants___NODE`]. Gatsby will use `variants___NODE`.
success building schema — 0.283 s
success createPages — 0.000 s
success createPagesStatefully — 0.042 s
success onPreExtractQueries — 0.005 s
success update schema — 0.019 s
success extract queries from components — 0.098 s
success run static queries — 0.021 s — 2/2 96.96 queries/second
success run page queries — 0.014 s — 4/4 301.32 queries/second
success write out page data — 0.012 s
success write out redirect data — 0.001 s
success Build manifest and related icons — 0.104 s
success onPostBootstrap — 0.106 s
info bootstrap finished - 23.946 s
WARNING Compiled with 1 warnings 6:04:43 PM
Module Warning (from ./node_modules/eslint-loader/index.js):
/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
2:10 warning 'useStaticQuery' is defined but never used no-unused-vars
2:26 warning 'graphql' is defined but never used no-unused-vars
✖ 2 problems (0 errors, 2 warnings)
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
You can now view gatsby-shopify in the browser.
http://localhost:8000/
View GraphiQL, an in-browser IDE, to explore your site's data and schema
http://localhost:8000/___graphql
Note that the development build is not optimized.
To create a production build, use npm run build
warning ⚠ 「wdm」:
info ℹ 「wdm」: Compiled with warnings.
WAIT Compiling... 6:04:43 PM
info ℹ 「wdm」: Compiling...
WARNING Compiled with 1 warnings 6:04:43 PM
Module Warning (from ./node_modules/eslint-loader/index.js):
/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
2:10 warning 'useStaticQuery' is defined but never used no-unused-vars
2:26 warning 'graphql' is defined but never used no-unused-vars
✖ 2 problems (0 errors, 2 warnings)
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
warning ⚠ 「wdm」:
info ℹ 「wdm」: Compiled with warnings.
gatsby-config.js:
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`
});
module.exports = {
siteMetadata: {
title: `Gatsby Shopify`,
description: `Gatsby Shopify Starter.`,
author: `#iamskok`,
},
plugins: [
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: "gatsby-source-graphql",
options: {
// This type will contain remote schema Query type
typeName: "ShopifyAdmin",
// This is field under which it's accessible
fieldName: "admin",
// Url to query from
url: `https://${process.env.SHOP_NAME}.myshopify.com/admin/api/2019-04/graphql.json`,
headers: {
// Learn about environment variables: https://gatsby.dev/env-vars
'X-Shopify-Access-Token': `${process.env.ADMIN_PASSWORD}`,
'Content-Type': 'application/graphql'
},
fetchOptions: {
method: 'POST'
},
refetchInterval: 60
},
},
{
resolve: `gatsby-source-shopify`,
options: {
// The domain name of your Shopify shop. This is required.
// Example: 'gatsby-source-shopify-test-shop' if your Shopify address is
// 'gatsby-source-shopify-test-shop.myshopify.com'.
shopName: process.env.SHOP_NAME,
// An API access token to your Shopify shop. This is required.
// You can generate an access token in the "Manage private apps" section
// of your shop's Apps settings. In the Storefront API section, be sure
// to select "Allow this app to access your storefront data using the
// Storefront API".
// See: https://help.shopify.com/api/custom-storefronts/storefront-api/getting-started#authentication
accessToken: process.env.STOREFRONT_ACCESS_TOKEN,
// Set verbose to true to display a verbose output on `npm run develop`
// or `npm run build`. This prints which nodes are being fetched and how
// much time was required to fetch and process the data.
// Defaults to true.
verbose: true,
},
},
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
],
}
./src/collections.js:
import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
const Collections = () => {
const storefrontData = useStaticQuery(
graphql`
query {
allShopifyCollection {
edges {
node {
id
description
descriptionHtml
handle
image {
altText
id
src
localFile {
childImageSharp {
fluid(maxWidth: 910) {
...GatsbyImageSharpFluid_withWebp_tracedSVG
}
}
}
}
products {
id
handle
title
}
title
updatedAt
}
}
}
}
`
)
const adminData = useStaticQuery(
graphql`
query {
admin {
shop {
name
}
}
}
`
)
console.log('storefront data:', JSON.stringify(storefrontData));
console.log('admin data:', JSON.stringify(adminData));
return (
<div className="collections">
<h2>Collections</h2>
</div>
)
}
export default Collections
index.js:
import React from 'react'
import Layout from '../components/layout'
import Collections from '../components/collections'
const IndexPage = () => (
<Layout>
<h1>Shopify</h1>
<Collections />
</Layout>
)
export default IndexPage
package.json:
{
"name": "gatsby-shopify",
"private": true,
"description": "Gatsby Shopify Starter",
"version": "0.1.0",
"author": "Vladimir Skok <skok#vova.io>",
"dependencies": {
"gatsby": "^2.4.2",
"gatsby-image": "^2.0.41",
"gatsby-plugin-manifest": "^2.1.1",
"gatsby-plugin-offline": "^2.1.0",
"gatsby-plugin-react-helmet": "^3.0.12",
"gatsby-plugin-sharp": "^2.0.36",
"gatsby-source-filesystem": "^2.0.33",
"gatsby-source-graphql": "^2.0.18",
"gatsby-source-shopify": "^2.0.28",
"gatsby-transformer-sharp": "^2.1.19",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-helmet": "^5.2.1"
},
"devDependencies": {
"prettier": "^1.17.0"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write src/**/*.{js,jsx}",
"start": "npm run develop",
"serve": "gatsby serve",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
},
"repository": {
"type": "git",
"url": "https://github.com/iamskok/gatsby-shopify-starter"
},
"bugs": {
"url": "https://github.com/iamskok/gatsby-shopify-starter/issues"
}
}
The expected result is to make a successful GraphQL query to Shopify Admin API. The actual result is server error with 400 status code.

Your gatsby-source-graphql setting is different than the curl command in the following seting:
the POST HTTP Method
Content-Type: application/graphql header
In order to match the curl command, you could try the setting below:
{
resolve: "gatsby-source-graphql",
options: {
typeName: "ShopifyAdmin",
fieldName: "admin",
url: `https://${process.env.SHOP_NAME}.myshopify.com/admin/api/2019-04/orders.json`,
headers: {
'X-Shopify-Access-Token': `${process.env.ADMIN_PASSWORD}`,
+ 'Content-Type': 'application/graphql',
},
+ fetchOptions: {
+ method: 'POST'
+ }
refetchInterval: 60
},
},

You have a few issues here.
First you need to pass X-Shopify-Storefront-Access-Token not X-Shopify-Access-Token. (
if you are really using a private app )
Then you need to request /api/2019-04/graphql not /admin/api/2019-04/graphql.json".
Please refer to this doc: https://help.shopify.com/en/api/custom-storefronts/storefront-api/getting-started#accessing-the-storefront-api-graphql-endpoint

Related

Error statement Page data from page-data.json for the failed page "/404/"

I get the following error when I do a gatsby build
➤ gatsby build
success compile gatsby files - 0.861s
success load gatsby config - 0.019s
success load plugins - 0.380s
warn gatsby-plugin-react-helmet: Gatsby now has built-in support for modifying the document head. Learn more at https://gatsby.dev/gatsby-head
success onPreInit - 0.007s
success delete worker cache from previous builds - 0.001s
info One or more of your plugins have changed since the last time you ran Gatsby. As
a precaution, we're deleting your site's cache to ensure there's no stale data.
success initialize cache - 0.071s
success copy gatsby files - 0.077s
success Compiling Gatsby Functions - 0.181s
success onPreBootstrap - 0.191s
success createSchemaCustomization - 0.088s
success Contentful: Sync all items - 0.145s - 5/5 34.43/s
success Contentful: Fetch data - 0.450s
info Contentful: 0 new entries
info Contentful: 3 updated entries
info Contentful: 0 deleted entries
info Contentful: 0 cached entries
info Contentful: 1 new assets
info Contentful: 1 updated assets
info Contentful: 0 cached assets
info Contentful: 0 deleted assets
info Creating 3 Contentful CompanyIndex nodes
info Creating 2 Contentful asset nodes
success Contentful: Create nodes - 0.023s
success Contentful: Process data - 0.043s
success Checking for changed pages - 0.000s
success source and transform nodes - 0.577s
info Writing GraphQL type definitions to /Users/koutarou/dev/Aries-front-gatsby/.cache/schema.gql
success building schema - 0.293s
success createPages - 0.010s
success createPagesStatefully - 0.058s
info Total nodes: 50, SitePage nodes: 7 (use --verbose for breakdown)
success Checking for changed pages - 0.000s
success Cleaning up stale page-data - 0.001s
success onPreExtractQueries - 0.000s
success extract queries from components - 1.302s
success write out redirect data - 0.002s
success onPostBootstrap - 0.001s
info bootstrap finished - 6.367s
success write out requires - 0.002s
success Building production JavaScript and CSS bundles - 16.210s
success Building HTML renderer - 18.689s
success Execute page configs - 0.244s
success Caching Webpack compilations - 0.001s
success run queries in workers - 0.148s - 11/11 74.15/s
success Merge worker state - 0.006s
success Rewriting compilation hashes - 0.053s
success Writing page-data.json files to public directory - 0.110s - 7/7 63.67/s
ERROR
Page data from page-data.json for the failed page "/404/": {
"componentChunkName": "component---src-pages-404-js",
"path": "/404/",
"result": {
"pageContext": {}
},
"staticQueryHashes": [
"744553348"
]
}
failed Building static HTML for pages - 2.654s
ERROR #95313
Building static HTML failed for path "/404/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
package.json is here.
{
"name": "",
"version": "1.0.0",
"private": true,
"description": "",
"author": "testUser",
"keywords": [
"gatsby"
],
"scripts": {
"develop": "gatsby develop",
"start": "gatsby develop",
"build": "gatsby build",
"serve": "gatsby serve",
"clean": "gatsby clean"
},
"dependencies": {
"#emotion/react": "^11.10.4",
"#emotion/styled": "^11.10.4",
"#mui/icons-material": "^5.10.6",
"#mui/material": "^5.10.8",
"#mui/styles": "^5.10.8",
"babel-plugin-styled-components": "^2.0.7",
"dotenv": "^16.0.3",
"gatsby": "^4.24.1",
"gatsby-plugin-google-gtag": "^4.24.0",
"gatsby-plugin-image": "^2.24.0",
"gatsby-plugin-react-helmet": "^5.24.0",
"gatsby-plugin-sharp": "^4.24.0",
"gatsby-plugin-sitemap": "^5.24.0",
"gatsby-plugin-styled-components": "^5.24.0",
"gatsby-source-contentful": "^7.22.0",
"gatsby-transformer-sharp": "^4.24.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-helmet": "^6.1.0",
"react-tabs": "^5.1.0",
"styled-components": "^5.3.6"
}
}
gatsby-config.js is here.
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
});
module.exports = {
siteMetadata: {
defaultTitle: "test page",
siteUrl: `https://www.example.com`,
author: `Lagopus`,
defaultDescription: "testtesttest",
defaultImage: "",
twitterUsername: "",
},
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
`gatsby-plugin-styled-components`,
`gatsby-plugin-sitemap`,
`gatsby-plugin-react-helmet`,
{
resolve: "gatsby-source-contentful",
options: {
accessToken: process.env.GATSBY_ACCESS_TOKEN,
spaceId: process.env.GATSBY_SPACE_ID,
},
},
{
resolve: "gatsby-plugin-google-gtag",
options: {
trackingId: [process.env.GATSBY_GA_MEASUREMENT_ID],
gtagConfig: {
optimize_id: [process.env.GATSBY_GTM_ID],
anonymize_ip: true,
cookie_expires: 0,
},
pluginConfig: {
head: true,
},
},
},
],
};
404.js is here.
import { Link } from "gatsby";
import * as React from "react";
import Layout from "../layouts";
import { default as Seo } from "../layouts/head";
const NotFoundPage = () => {
return (
<Layout>
<Link to="/">Go home</Link>.
</Layout>
);
};
export default NotFoundPage;
export const Head = () => <Seo title="home page" />;
Here is the information on the 404 page that will be created after the build.
// /public/component---src-pages-404-js-060c466843a77c0728e6.js
"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[883],{429:function(e,t,n){n.r(t),n.d(t,{Head:function(){return l}});var r=n(1082),u=n(7294),c=n(1823),a=n(9152);t.default=function(){return u.createElement(c.Z,null,u.createElement(r.rU,{to:"/"},"Go home"),".")};var l=function(){return u.createElement(a.Z,{title:"Home page"})}}}]);
//# sourceMappingURL=component---src-pages-404-js-060c466843a77c0728e6.js.map
// /public/component---src-pages-404-js-060c466843a77c0728e6.js.map
{"version":3,"file":"component---src-pages-404-js-060c466843a77c0728e6.js","mappings":"8KAaA,UARqB,WACnB,OACE,gBAAC,IAAD,KACE,gBAAC,KAAD,CAAMA,GAAG,KAAT,WADF,IAIH,EAIM,IAAMC,EAAO,kBAAM,gBAAC,IAAD,CAAKC,MAAM,QAAjB,C","sources":["webpack:///./src/pages/404.js"],"sourcesContent":["import { Link } from \"gatsby\";\nimport * as React from \"react\";\nimport Layout from \"../layouts\";\nimport { default as Seo } from \"../layouts/head\";\n\nconst NotFoundPage = () => {\n return (\n <Layout>\n <Link to=\"/\">Go home</Link>.\n </Layout>\n );\n};\n\nexport default NotFoundPage;\n\nexport const Head = () => <Seo title=\"home page\" />;\n"],"names":["to","Head","title"],"sourceRoot":""}
When I comment out gatsby-plugin-google-gtag in gatsby-config.js and then build, it passes without problems, so I think the problem is in gatsby-plugin-google-gtag, but I cannot figure out the cause.
If you need any other information, please let me know.
You have a typo in the configuration for your gatsby-plugin-google-gtag plugin: trackingId should be trackingIds (note the trailing S)
{
resolve: "gatsby-plugin-google-gtag",
options: {
trackingIds: [process.env.GATSBY_GA_MEASUREMENT_ID],
gtagConfig: {
optimize_id: [process.env.GATSBY_GTM_ID],
anonymize_ip: true,
cookie_expires: 0,
},
pluginConfig: {
head: true,
},
},
},

Synpress cannot use cy.acceptMetamaskAccess (is not a function)

I'm trying to use Synpress, but I fail to understand how to solve
TypeError: cy.acceptMetamaskAccess is not a function
Let me share the relevant code* (I mostly followed this tutorial https://medium.com/andamp/how-to-setup-synpress-for-wen3-dapp-frontend-test-automation-with-metamask-73396896684a)
*if something is missing, please let me know
package.json:
{
"devDependencies": {
"#testing-library/cypress": "^8.0.2",
"cypress": "^9.7.0"
},
"scripts": {
"cypress:open": "cypress open",
"test": "env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='tests/support/index.js'",
"test:watch": "env-cmd -f .env npx synpress open -cf synpress.json"
},
"dependencies": {
"#synthetixio/synpress": "^1.2.0",
"env-cmd": "^10.1.0"
}
}
How I configured my synpress.json
{
"baseUrl": "https://dappify.com/",
"userAgent": "synpress",
"retries": { "runMode": 0, "openMode": 0 },
"integrationFolder": "tests/integration",
"screenshotsFolder": "screenshots",
"videosFolder": "videos",
"video": true,
"chromeWebSecurity": true,
"viewportWidth": 1366,
"viewportHeight": 850,
"component": {
"componentFolder": ".",
"testFiles": "**/*spec.{js,jsx,ts,tsx}"
},
"env": {
"coverage": false
},
"defaultCommandTimeout": 30000,
"pageLoadTimeout": 30000,
"requestTimeout": 30000,
"supportFile": "tests/support/index.js"
}
Simple test
describe('Test User Login', () => {
it('Connects with Metamask', () => {
cy.visit('https://dappify.com')
cy.contains('Sign').click();
cy.contains('Confirm').click();
cy.contains('Connect Wallet').click();
cy.contains('Metamask').click();
cy.switchToMetamaskWindow();
cy.acceptMetamaskAccess().should("be.true");
})
})
I don't understand why cy.acceptMetamaskAccess() is not a function, I can find it here: https://github.com/synthetixio/synpress/blob/master/support/index.d.ts
How can I use the functions listed in this index.d.ts file?
** Solution **
Answer by Fody was helpful! Let me summarise the steps needed:
inside support folder you need an index.js
inside index.js
import './commands'
import "#synthetixio/synpress/support";
If you want to add custom functions add this file to support too
inside commands.js:
import "#testing-library/cypress/add-commands";
// here go(es) your custom function(s)
It's a bit hard to untangle the Synpress structure. Usually with a plugin library you import a support component and that adds the library's custom commands to your test.
The article says
Run your tests with env-cmd -f .env npx synpress run -cf synpress.json --config supportFile='support/index.js'
which makes me think the last parameter is bringing in the custom commands.
If you already tried that, the following is the command definition, you can try adding it at the top of your spec.
Cypress.Commands.add('acceptMetamaskAccess', allAccounts => {
return cy.task('acceptMetamaskAccess', allAccounts);
})

Electron-Prisma Error: can not find module '.prisma/client'

I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB

Unable to resolve module in react-viro

I'm trying to run this app and I get the following error!
https://github.com/vnovick/pile-blocks-ar
I checked the proper asset import instruction from here https://docs.viromedia.com/docs/importing-assets
everything seems legit but I keep getting the error!
===
error: bundling failed: Error: Unable to resolve module ./res/tetris/blocks_1.vrx from /Users/###/pile-blocks-ar-master/js/GameSceneAR.js: The module ./res/tetris/blocks_1.vrx could not be found from /Users/###/pile-blocks-ar-master/js/GameSceneAR.js. Indeed, none of these files exist:
`/Users/###/pile-blocks-ar-master/js/res/tetris/blocks_1.vrx
...
===
I change the versions in package.json to the latest:
"react": "16.6.1",
"react-native": "0.57.7",
"react-viro": "2.13.0"
Thanks in advance :)
You need to add assets support manualy if you have imported ViroAR in existing React-Native app (not created with Viro CLI).
Here's the guide:
https://docs.viromedia.com/docs/importing-assets
If you are using RN > 0.59 then you should discard viro instructions and modify metro.config.js file (located in project root) to look something like this:
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
module.exports = {
resolver: {
assetExts: [
'obj',
'mtl',
'JPG',
'vrx',
'hdr',
'gltf',
'glb',
'bin',
'arobject',
'png',
],
},
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: false,
},
}),
},
};
resolver.assetExts is the key.

Nuxt Error: Syntax Unexpected token export after installation

I am using Nuxt for my Vue project, It was working fine. I deleted my yarn and NPM cache due to other project issues. I re-installed the packages for my Nuxt app. The app is Universal and Uses express. Installation and Dev server is running, but when I try to visit http://localhost:3000/,
The error:
SyntaxError: Unexpected token export, shows up every time.
I know this is babel issue but I don't how to resolve this issue on Nuxt.
Nuxt Configuration:
const pkg = require('./package')
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [
'element-ui/lib/theme-chalk/index.css',
'#mdi/font/css/materialdesignicons.min.css'
],
/*
** Plugins to load before mounting the App
*/
plugins: [
'#/plugins/element-ui',
'~/plugins/vee-validate.js'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'#nuxtjs/axios',
'#nuxtjs/apollo'
],
apollo: {
tokenName: 'yourApolloTokenName', // optional, default: apollo-token
tokenExpires: 10, // optional, default: 7
includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
authenticationType: 'Basic', // optional, default: 'Bearer'
// optional
errorHandler (error) {
console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
},
// required
clientConfigs: {
default: {
// required
httpEndpoint: 'http://localhost:4000',
// optional
// See https://www.apollographql.com/docs/link/links/http.html#options
httpLinkOptions: {
credentials: 'same-origin'
},
// You can use `wss` for secure connection (recommended in production)
// Use `null` to disable subscriptions
wsEndpoint: null, // optional
// LocalStorage token
tokenName: 'apollo-token', // optional
// Enable Automatic Query persisting with Apollo Engine
persisting: false, // Optional
// Use websockets for everything (no HTTP)
// You need to pass a `wsEndpoint` for this to work
websocketsOnly: false // Optional
},
test: {
httpEndpoint: 'http://localhost:5000',
wsEndpoint: 'ws://localhost:5000',
tokenName: 'apollo-token'
},
// alternative: user path to config which returns exact same config options
}
},
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
}
}
My package.json file
{
"name": "app",
"version": "1.0.0",
"description": "My exceptional Nuxt.js project",
"author": "Saima",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#mdi/font": "^3.3.92",
"#nuxtjs/apollo": "^4.0.0-rc2.3",
"#nuxtjs/axios": "^5.0.0",
"cross-env": "^5.2.0",
"element-ui": "^2.4.6",
"express": "^4.16.3",
"graphql-tag": "^2.10.1",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"nuxt": "^2.0.0",
"vee-validate": "^2.1.5"
},
"devDependencies": {
"babel-preset-env": "^1.7.0",
"babel-register": "^6.26.0",
"nodemon": "^1.11.0"
}
}
Help would be appreciated.
I just checked your issue and it happens when you use element UI with Nuxt. Update your Nuxt configuration like this(Andrew Answer):
plugins: [
{src: '~/plugins/element-ui', ssr: false},
{src: '~/plugins/vee-validate.js', ssr: true},
],
This error can show up if you're importing an ES6 module which needs to be transpiled in order to load into the UI. In that case, this is fixed by adding the module into the transpile key of the build section of nuxt.config.js (at time of this post, the Nuxt transpile docs are a little confusing).
For instance, if you're trying to import a module called #stylelib then you'd want the following in your nuxt.config.js:
export default {
...
build: {
...
transpile: ['#stylelib']
}
}
I had the same issue and it was found in my nuxt.config.js file where i had placed some extra code with a ',' at the end of that code. The code in question was at the top of the file.
The code:
env: {
strapiBaseUri: process.env.API_URL || "http://localhost:1337"
},
My setup details are:
Nuxtjs (version as of March 20, 2020)
Apollo and Graphql
Strapi (backend)
For me (typescript Nuxt) it was using:
npm run start
instead of:
npm run dev

Categories