I am trying run rocket.chat on CentOS 7. But it throw exception:
I20191120-09:44:42.581(7)? Exception in callback of async function: TypeError: Cannot destructure property `OAuth2` of 'undefined' or 'null'.
I20191120-09:44:42.582(7)? at routes.js (app/livestream/server/routes.js:8:27)
I20191120-09:44:42.582(7)? at fileEvaluate (packages/modules-runtime.js:336:7)
I20191120-09:44:42.582(7)? at Module.require (packages/modules-runtime.js:238:14)
I20191120-09:44:42.582(7)? at Module.moduleLink [as link] (/root/.meteor/packages/modules/.0.13.0.1ny9ohg.lqq5++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/reify/lib/runtime/index.js:38:38)
I20191120-09:44:42.582(7)? at index.js (app/livestream/server/index.js:1:8)
I20191120-09:44:42.583(7)? at fileEvaluate (packages/modules-runtime.js:336:7)
I20191120-09:44:42.583(7)? at Module.require (packages/modules-runtime.js:238:14)
I20191120-09:44:42.583(7)? at Module.moduleLink [as link] (/root/.meteor/packages/modules/.0.13.0.1ny9ohg.lqq5++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/reify/lib/runtime/index.js:38:38)
I20191120-09:44:42.583(7)? at importPackages.js (server/importPackages.js:1:1667)
I20191120-09:44:42.584(7)? at fileEvaluate (packages/modules-runtime.js:336:7)
I20191120-09:44:42.584(7)? at Module.require (packages/modules-runtime.js:238:14)
I20191120-09:44:42.584(7)? at Module.moduleLink [as link] (/root/.meteor/packages/modules/.0.13.0.1ny9ohg.lqq5++os+web.browser+web.browser.legacy+web.cordova/npm/node_modules/reify/lib/runtime/index.js:38:38)
I20191120-09:44:42.584(7)? at main.js (server/main.js:1:8)
I20191120-09:44:42.584(7)? at fileEvaluate (packages/modules-runtime.js:336:7)
I20191120-09:44:42.585(7)? at Module.require (packages/modules-runtime.js:238:14)
I20191120-09:44:42.585(7)? at require (packages/modules-runtime.js:258:21)
I20191120-09:44:42.585(7)? at /usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/app/app.js:145189:15
I20191120-09:44:42.585(7)? at /usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/boot.js:419:36
I20191120-09:44:42.585(7)? at Array.forEach (<anonymous>)
I20191120-09:44:42.586(7)? at /usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/boot.js:228:19
I20191120-09:44:42.586(7)? at /usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/boot.js:479:5
I20191120-09:44:42.586(7)? at Function.run (/usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/profile.js:510:12)
I20191120-09:44:42.586(7)? at /usr/app_chat/Rocket.Chat/.meteor/local/build/programs/server/boot.js:478:11
import { Meteor } from 'meteor/meteor';
import google from 'googleapis';
import { settings } from '../../settings';
import { Users } from '../../models';
import { API } from '../../api';
const { OAuth2 } = google.auth;
API.v1.addRoute('livestream/oauth', {
get: function functionName() {
const clientAuth = new OAuth2(settings.get('Broadcasting_client_id'), settings.get('Broadcasting_client_secret'), `${ settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api'));
const { userId } = this.queryParams;
const url = clientAuth.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/youtube'],
state: JSON.stringify({
userId,
}),
});
return {
statusCode: 302,
headers: {
Location: url,
},
body: 'Oauth redirect',
};
},
});
API.v1.addRoute('livestream/oauth/callback', {
get: function functionName() {
const { code, state } = this.queryParams;
const { userId } = JSON.parse(state);
const clientAuth = new OAuth2(settings.get('Broadcasting_client_id'), settings.get('Broadcasting_client_secret'), `${ settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api'));
const ret = Meteor.wrapAsync(clientAuth.getToken.bind(clientAuth))(code);
Users.update({ _id: userId }, { $set: {
'settings.livestream': ret,
} });
return {
headers: {
'content-type': 'text/html',
},
body: '<script>window.close()</script>',
};
},
});
Like https://stackoverflow.com/users/7080548/sebastian-kaczmarek already indicated, you need to replace:
import google from 'googleapis';
with
import { google } from 'googleapis';
Also see
https://www.npmjs.com/package/googleapis#first-example
Related
I'm trying to use Apollo Client/Server for my NextJS, and some pages I'm trying to SSR and staticlly generate them, but I'm faing an issue with Apollo where it fails to fetch on server but not when I use the client on the client.
Firstlly this is my package json, where my libs are configed:
{
"name": "landing",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev -p 9999",
"build": "next build",
"start": "next start -p 9999",
"lint": "next lint"
},
"dependencies": {
"#apollo/react-hooks": "^4.0.0",
"#reduxjs/toolkit": "^1.9.0",
"apollo-server-micro": "2.25.1",
"deepmerge": "^4.2.2",
"firebase": "^9.14.0",
"graphql": "^15.5.1",
"loadash": "^1.0.0",
"luxon": "^3.1.1",
"mongoose": "^5.13.15",
"next": "11.0.1",
"next-redux-wrapper": "^8.0.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-images-uploading": "^3.1.7",
"react-infinite-scroll-component": "^6.1.0",
"react-redux": "^8.0.5",
"react-tag-input-component": "^2.0.2",
"uuid": "^9.0.0"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"eslint": "7.32.0",
"eslint-config-next": "11.0.1",
"postcss": "^8.4.19"
}
}
And here is my single API route in pages/api.jsx folder:
import { Connect } from "../utils/Connect";
import { ApolloServer, makeExecutableSchema } from "apollo-server-micro";
import { defs as typeDefs } from "../graphql/defs";
import { resolves as resolvers } from "../graphql/resolves";
Connect();
export const schema = makeExecutableSchema({ typeDefs, resolvers });
const api = { bodyParser: false };
const path = { path: "/api" };
export const config = { api };
export default new ApolloServer({ schema }).createHandler(path);
While this is my Mongo Connection that I imported earlier:
import mongoose from "mongoose";
export const Connect = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
} catch (err) {
console.log(`Something went wrong trying to connect to the database);
process.exit(1);
}
};
While this is my Apollo Client which is configured for Client and Server calls:
import merge from "deepmerge";
import { useMemo } from "react";
import { ApolloClient, HttpLink, InMemoryCache, from } from "#apollo/client";
import { onError } from "#apollo/client/link/error";
import { concatPagination } from "#apollo/client/utilities";
import { isEqual } from "lodash";
export const APOLLO_STATE_PROP_NAME = "__APOLLO_STATE__";
let apolloClient;
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) graphQLErrors.forEach(({ message, locations, path }) => {
const msg = `[GraphQL error]: Message: ${message}`;
const lct = `Location: ${locations}`;
const pth = `Path: ${path}`;
console.log(`${msg}, ${lct}, ${pth}`);
});
if (networkError) {
const ntw = `[Network error]: ${networkError}`;
console.log(ntw);
}
});
const httpLink = new HttpLink({
uri: `http://localhost:9999/api`,
credentials: "same-origin",
});
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: from([errorLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
},
},
}),
});
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient();
if (initialState) {
const existingCache = _apolloClient.extract();
const data = merge(existingCache, initialState, {
arrayMerge: (destinationArray, sourceArray) => [
...sourceArray,
...destinationArray.filter((d) =>
sourceArray.every((s) => !isEqual(d, s))
),
],
});
_apolloClient.cache.restore(data);
}
if (typeof window === "undefined") return _apolloClient;
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function addApolloState(client, pageProps) {
if (pageProps?.props) pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();
return pageProps;
}
export function useApollo(pageProps) {
const state = pageProps[APOLLO_STATE_PROP_NAME];
const store = useMemo(() => initializeApollo(state), [state]);
return store;
}
And lately, this is my page that is SSR-ing:
import { Category } from "../../ui/pages";
import { addApolloState, initializeApollo } from "../../config/Apollo";
import { Description, Globals, Title } from "../../config/Metas";
import { CATEGORIES, CATEGORY } from "../../graphql/queries";
export async function getStaticPaths() {
let paths = [];
const Apollo = initializeApollo();
const config = { query: CATEGORIES };
const categories = await Apollo.query(config);
paths = categories.data.Categories.map((category) => {
return {
params: {
category: category.Name.toLowerCase(),
...category,
},
};
});
return {
paths,
fallback: false,
};
}
export async function getStaticProps(context) {
const Apollo = initializeApollo();
const slug = context.params.category;
const category = await Apollo.query({
query: CATEGORY,
variables: { slug },
});
if (category) {
const data = { props: { category } };
return addApolloState(Apollo, data);
}
else return {
notFound: true,
};
}
const Route = ({ category }) => {
const { data } = category;
const { Category: Meta } = data;
return (
<>
<Globals />
<Title title={Meta.Name} />
<Description description={Meta.Description} />
<Category />
</>
);
};
export default Route;
All those queries that I call are being tested on the Apollo client on front and they are working, but when I do this and start the server with npm run dev I get a weird error:
[Network error]: TypeError: fetch failed
Error [ApolloError]: fetch failed
at new ApolloError (/Users/bfzli/Code/landdding/node_modules/#apollo/client/errors/errors.cjs:34:28)
at /Users/bf/Code/landing/node_modules/#apollo/client/core/core.cjs:1800:19
at both (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:997:53)
at /Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:990:72
at new Promise (<anonymous>)
at Object.then (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:990:24)
at Object.error (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:998:49)
at notifySubscription (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:140:18)
at onNotify (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:179:3)
at SubscriptionObserver.error (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:240:7) {
type: 'ApolloError',
graphQLErrors: [],
clientErrors: [],
networkError: {
cause: {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 9999
}
}
}
I am getting this error message while trying to learn how to test next.js applications
I have tried import the Text Encoder from utils at the top of the config as well as test file with no success
ReferenceError: TextEncoder is not defined
at Object.<anonymous> (node_modules/whatwg-url/lib/encoding.js:2:21)
at Object.<anonymous> (node_modules/whatwg-url/lib/url-state-machine.js:5:34)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL-impl.js:2:13)
at Object.<anonymous> (node_modules/whatwg-url/lib/URL.js:442:14)
at Object.<anonymous> (node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Object.<anonymous> (node_modules/whatwg-url/index.js:3:34)
at Object.<anonymous> (node_modules/mongodb-connection-string-url/src/index.ts:1:1)
at Object.<anonymous> (node_modules/mongodb/src/connection_string.ts:3:1)
at Object.<anonymous> (node_modules/mongodb/src/mongo_client.ts:11:1)
at Object.<anonymous> (node_modules/mongodb/src/change_stream.ts:17:1)
at Object.<anonymous> (node_modules/mongodb/src/index.ts:3:1)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js:8:16)
at Object.<anonymous> (node_modules/mongoose/lib/drivers/node-mongodb-native/index.js:7:18)
at Object.<anonymous> (node_modules/mongoose/lib/index.js:7:25)
at Object.<anonymous> (node_modules/mongoose/index.js:8:18)
at Object.<anonymous> (library/mongoDB.js:15:56)
at Object.<anonymous> (library/players.js:15:18)
at Object.<anonymous> (pages/index.js:18:18)
at Object.<anonymous> (tests/index.test.js:6:53)
Jest Config File
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
}
module.exports = createJestConfig(customJestConfig)
Package.json
"devDependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"eslint": "8.23.1",
"eslint-config-next": "12.3.0",
"jest": "^29.1.1",
"jest-environment-jsdom": "^29.1.1"
}
index.test.js
import Home from '../pages/index'
import '#testing-library/jest-dom'
import { fireEvent, render, screen } from '#testing-library/react'
describe('Home Page', () => {
it('renders home component',
() => {
render(<Home />)
expect(screen.getByTestId('home-page')).toBeInTheDocument()
})
})
I would do it by mocking TextEncoder on a dedicated file which will be placed as a setup file on jest config.
This way I think you should get rid of that error.
// text-encoder.mock.ts
import { TextEncoder } from 'util';
global.TextEncoder = TextEncoder;
// jest.config.ts
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './',
});
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
setupFiles: [
'<rootDir>/path/to/text-encoder.mock.ts',
],
};
module.exports = createJestConfig(customJestConfig)
I'm pretty new to testing UI elements and I'm at a loss here. I have a component, ProjectDashboardView, that fetches some information from an API on mount and renders a series of ProjectDashboardCard components with that fetched information. I'm mocking the API call on the tests, using flush-promises to wait for all promises to be resolved before assertion. However, I'm getting this error:
● projectDashboardView › displays ProjectDashboardCards corresponding to all the repositories fetched
TypeError: Cannot read properties of undefined (reading 'component')
14 | describe('projectDashboardView', () => {
15 | it('displays ProjectDashboardCards corresponding to all the repositories fetched', async () => {
> 16 | const wrapper = await mount(ProjectDashboardView, {
| ^
17 | router,
18 | localVue,
19 | mocks: {
at remapInternalIcon (node_modules/vuetify/dist/webpack:/Vuetify/src/util/helpers.ts:233:39)
at VueComponent.getIcon (node_modules/vuetify/dist/webpack:/Vuetify/src/components/VIcon/VIcon.ts:72:31)
at Proxy.render (node_modules/vuetify/dist/webpack:/Vuetify/src/components/VIcon/VIcon.ts:217:23)
at VueComponent.Vue._render (node_modules/vue/dist/vue.runtime.common.dev.js:3559:22)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:21)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at init (node_modules/vue/dist/vue.runtime.common.dev.js:3131:13)
at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:6002:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5949:9)
at createChildren (node_modules/vue/dist/vue.runtime.common.dev.js:6077:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5978:9)
at createChildren (node_modules/vue/dist/vue.runtime.common.dev.js:6077:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5978:9)
at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6499:7)
at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3948:19)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:10)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at init (node_modules/vue/dist/vue.runtime.common.dev.js:3131:13)
at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:6002:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5949:9)
at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6499:7)
at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3948:19)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:10)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at init (node_modules/vue/dist/vue.runtime.common.dev.js:3131:13)
at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:6002:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5949:9)
at createChildren (node_modules/vue/dist/vue.runtime.common.dev.js:6077:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5978:9)
at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6499:7)
at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3948:19)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:10)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at init (node_modules/vue/dist/vue.runtime.common.dev.js:3131:13)
at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:6002:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5949:9)
at createChildren (node_modules/vue/dist/vue.runtime.common.dev.js:6077:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5978:9)
at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6499:7)
at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3948:19)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:10)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at init (node_modules/vue/dist/vue.runtime.common.dev.js:3131:13)
at createComponent (node_modules/vue/dist/vue.runtime.common.dev.js:6002:9)
at createElm (node_modules/vue/dist/vue.runtime.common.dev.js:5949:9)
at VueComponent.patch [as __patch__] (node_modules/vue/dist/vue.runtime.common.dev.js:6499:7)
at VueComponent.Vue._update (node_modules/vue/dist/vue.runtime.common.dev.js:3948:19)
at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4069:10)
at Watcher.get (node_modules/vue/dist/vue.runtime.common.dev.js:4481:25)
at new Watcher (node_modules/vue/dist/vue.runtime.common.dev.js:4470:12)
at mountComponent (node_modules/vue/dist/vue.runtime.common.dev.js:4076:3)
at VueComponent.Object.<anonymous>.Vue.$mount (node_modules/vue/dist/vue.runtime.common.dev.js:8436:10)
at mount (node_modules/#vue/test-utils/dist/vue-test-utils.js:14057:21)
Here's the code for both the test and the component:
ProjectDashboardView.spec.js
import { mount, createLocalVue } from '#vue/test-utils'
import { SERVICES } from '#/utils/common'
import VueRouter from 'vue-router'
import router from '#/router'
import flushPromises from 'flush-promises'
import ProjectDashboardView from '#/components/ProjectDashboard/ProjectDashboardView.vue'
import ProjectDashboardCard from '#/components/ProjectDashboard/ProjectDashboardCard.vue'
jest.mock('#/services/finderService')
const localVue = createLocalVue()
localVue.use(VueRouter)
describe('projectDashboardView', () => {
it('displays ProjectDashboardCards corresponding to all the repositories fetched', async () => {
const wrapper = mount(ProjectDashboardView, {
router,
localVue,
mocks: {
$store: {
state: {
user: {
name: '',
// Array of IDs
repositories: [1, 2],
// Services the user is using to test code quality in their projects
services: SERVICES,
},
},
},
},
})
await flushPromises()
const children = wrapper.findAllComponents(ProjectDashboardCard)
expect(children.length).toBeGreaterThan(0)
})
})
ProjectDashboardView.js
<template>
<v-container class="grid">
<project-dashboard-card
v-for="(value, name) in latestReports"
:key="name"
:repository="value"
/>
<the-add-project-button />
</v-container>
</template>
<script>
import finderService from '#/services/finderService'
import ProjectDashboardCard from '#/components/ProjectDashboard/ProjectDashboardCard'
import TheAddProjectButton from '#/components/ProjectDashboard/TheAddProjectButton'
import { mapState } from 'vuex'
export default {
name: 'ProjectDashboardView',
components: {
ProjectDashboardCard,
TheAddProjectButton,
},
data() {
return {
latestReports: [],
}
},
computed: {
...mapState(['user']),
},
mounted() {
this.fetchLatestReports()
},
methods: {
fetchLatestReports() {
const reportTuples = []
for (const repo of this.user.repositories) {
for (const service of this.user.services) {
reportTuples.push([service, repo])
}
}
const allReports = Promise.all(
reportTuples.map(t => finderService.find(t[0], t[1], true))
)
const latestReports = {}
allReports
.then(responses => {
const filteredResponses = responses.filter(
response => response.data.length > 0
)
filteredResponses.forEach(response => {
if (!latestReports[`repo${response.repoID}`]) {
latestReports[`repo${response.repoID}`] = {}
}
if (!latestReports[`repo${response.repoID}`].repoName) {
latestReports[`repo${response.repoID}`].repoName =
response.data[0].project_name
}
if (!latestReports[`repo${response.repoID}`].services) {
latestReports[`repo${response.repoID}`].services =
{}
}
latestReports[`repo${response.repoID}`].services[
response.service
] = response.data[0]
})
this.latestReports = latestReports
})
.catch(err => console.log(err))
},
},
}
</script>
Just in case, here's the code for the API call mock too:
import sonarqubeReport from './fixtures/find.sonarqube.1.json'
import gitleaksReport from './fixtures/find.gitleaks.1.json'
import dependencycheckReport from './fixtures/find.dependencycheck.1.json'
import hadolintReport from './fixtures/find.hadolint.1.json'
import trivyReport from './fixtures/find.trivy.1.json'
const mockGetResponse = service => {
switch (service) {
case 'sonarqube':
return sonarqubeReport
case 'gitleaks':
return gitleaksReport
case 'dependencycheck':
return dependencycheckReport
case 'hadolint':
return hadolintReport
case 'trivy':
return trivyReport
default:
break
}
}
const finderService = {
find: service => Promise.resolve({ body: mockGetResponse(service) }),
}
export default finderService
I am trying to run the sample program 'Data Management with SQLite and Vuex in a NativeScript-Vue App'
https://nativescript.org/blog/data-management-with-sqlite-and-vuex-in-a-nativescript-vue-app/
I am getting the below error, please help in fixing this issue.
An uncaught Exception occurred on "main" thread.
Unable to start activity ComponentInfo{org.nativescript.preview/com.tns.NativeScriptActivity}:
com.tns.NativeScriptException: Calling js method onCreate failed
TypeError: Cannot read property 'state' of undefined
StackTrace:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{org.nativescript.preview/com.tns.NativeScriptActivity}: com.tns.NativeScriptException:
Calling js method onCreate failed
TypeError: Cannot read property 'state' of undefined
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3762)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3938)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at
android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2277)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: com.tns.NativeScriptException: Calling js method onCreate failed
TypeError: Cannot read property 'state' of undefined
at com.tns.Runtime.callJSMethodNative(Native Method)
at com.tns.Runtime.dispatchCallJSMethodNative(Runtime.java:1286)
at com.tns.Runtime.callJSMethodImpl(Runtime.java:1173)
at com.tns.Runtime.callJSMethod(Runtime.java:1160)
at com.tns.Runtime.callJSMethod(Runtime.java:1138)
at com.tns.Runtime.callJSMethod(Runtime.java:1134)
at com.tns.NativeScriptActivity.onCreate(NativeScriptActivity.java:20)
at android.app.Activity.performCreate(Activity.java:8183)
at android.app.Activity.performCreate(Activity.java:8167)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3735)
... 11 more
store.js is inside src folder.
store.js :
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
}
});
I have created a folder store inside src folder and created index.js file inside store folder. code is :
import Vue from 'nativescript-vue';
import Vuex from 'vuex';
const Sqlite = require( "nativescript-sqlite" );
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
database: null,
data: []
},
mutations: {
init(state, data) {
state.database = data.database;
},
load(state, data) {
state.data = [];
for(var i = 0; i < data.data.length; i++) {
state.data.push({
firstname: data.data[i][0],
lastname: data.data[i][1]
});
}
},
save(state, data) {
state.data.push({
firstname: data.data.firstname,
lastname: data.data.lastname
});
},
},
actions: {
init(context) {
(new Sqlite("my.db")).then(db => {
db.execSQL("CREATE TABLE IF NOT EXISTS people (id INTEGER
PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)").then(id => {
context.commit("init", { database: db });
}, error => {
console.log("CREATE TABLE ERROR", error);
});
}, error => {
console.log("OPEN DB ERROR", error);
});
},
insert(context, data) {
context.state.database.execSQL("INSERT INTO people (firstname,
lastname) VALUES (?, ?)", [data.firstname, data.lastname]).then(id => {
context.commit("save", { data: data });
}, error => {
console.log("INSERT ERROR", error);
});
},
query(context) {
context.state.database.all("SELECT firstname, lastname FROM people", []).then(result => {
context.commit("load", { data: result });
}, error => {
console.log("SELECT ERROR", error);
});
}
}
});
Vue.prototype.$store = store;
module.exports = store;
store.dispatch("init");
Try the following in the main.ts or main.js file:
import store from "./store";
new Vue({
store,
render: h => h('frame', [h(App))]),
}).$start();
Am porting over my meteor project to use ecmascript instead of using webpack / babel. Also upgrading my meteor (from 1.4 to 1.7) and react (from 15.3.2 to 16.8.6) too.
routes.jsx
import * as React from 'react';
export default function (injectDeps, {Store, Routes}) {
const route = {
path: 'tickets',
onEnter: (nextState, replace) => {
if (!Meteor.userId() || !Roles.userIsInRole(Meteor.userId(), 'staff', Roles.GLOBAL_GROUP)) {
replace('/login');
}
},
getComponent(nextState, cb) {
require.ensure([], (require) => {
Store.injectReducer('tickets', require('./reducers'));
cb(null, require('./containers/list.js'));
}, 'tickets');
},
childRoutes: [
{
path: ':_id',
getComponent(nextState, cb) {
require.ensure([], (require) => {
Store.injectReducer('tickets', require('./reducers'));
cb(null, require('./containers/view.js'));
}, 'tickets.view');
}
}
]
};
Routes.injectChildRoute(route);
}
Got this error:
Uncaught TypeError: require.ensure is not a function
at Object.getComponent (routes.jsx:20)
at getComponentsForRoute (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:38035)
at modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:38053
at modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:37842
at Array.forEach (<anonymous>)
at mapAsync (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:37841)
at getComponents (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:38052)
at finishEnterHooks (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:37263)
at next (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:37810)
at loopAsync (modules.js?hash=d04d5856a2fe2fa5c3dc6837e85d41adc321ecb2:37814
Any suggestion how to port this?
This is how it was done to get rid of require.ensure:
routes.jsx (final)
{
path: 'config',
getComponent(nextState, cb) {
import('./containers/config').then(mod => {
Store.injectReducer('config', require('./reducers/config').default);
cb(null, mod.default);
});
}
}
NOTE:
1) This is how the to migrate from require.ensure (used by webpack) to without relying on webpack (which was my case as am fully using Meteor Atmosphere to run)
2) mod and require(...).xxx had changed to mod.default and require(...).default if reducer function is exported as export default, otherwise said reducer will not be called.