Property 'start' does not exist on type 'ApolloServer' - visual-studio-code

I'm probably missing an obvious setting or something, but for some reason VS Code doesn't see ApolloServer.start, and I get an inline error:
Property 'start' does not exist on type 'ApolloServer'.
Can anyone see what I'm missing? It works by calling the usual listen method on the server, but I'm trying to add middleware, and this is the documented flow at apollo's official docs.
tsconfig
{
"compilerOptions": {
"baseUrl": ".",
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"types": ["node"],
"esModuleInterop": true,
},
"include": [
"apollo-server/*"
],
"exclude": ["node_modules"]
}
index.ts
#!/usr/bin/env node
import express from 'express'
import { ApolloServer, gql } from 'apollo-server-express'
import { readFileSync } from 'fs'
import { resolvers } from './resolvers'
const typeDefs = gql`readFileSync('./schema.graphql').toString('utf-8')`
async function startServer() {
const server = new ApolloServer({
typeDefs,
resolvers,
})
await server.start() // <---- VSCode complains here
const app = express()
server.applyMiddleware({ app })
}

UPDATE
This question was regarding Apollo Server 2.0. The links have since been changed and Apollo is now on in version 3.0. If you're not dependent on version 2, I suggest updating your dependency to v3. For those of you stuck on this, here's the pattern:
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
const server = new ApolloServer({ typeDefs, resolvers });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Here's a fresh URL to confirm it in the docs
FWIW, I found it right after I posted the question. This is a deprecated pattern. (Stale link removed)

Related

error on load RestClient on Azure devops extension dev

Im new in extensión dev for #azure #DevOps, I already publish one, the extensión by now can save and get documents via
VSS.getService(VSS.ServiceIds.ExtensionData).then(function (
dataService: any
) {...});
I want to get all teams from the project,and I have 2 problems, First I try to import the Rest client like this:
import RestClient = require("TFS/WorkItemTracking/RestClient");
But, When I upload to azure Devops and display the page in the consle say:
index.js:1 Uncaught ReferenceError: define is not defined
at index.js:1:1
Second I dont relly know how to use the getTeams function, I try this, but I can not test it, If u could give me an example would be great
var client = RestClient.getClient();
client.getTeams(VSS.getWebContext().project.id).then(function(getTeams){console.log(getTeams)})
I try another API and it works like this:
VSS.require(["VSS/Service", "TFS/WorkItemTracking/RestClient"], function (VSS_Service:any, TFS_Wit_WebApi:any) {
// Get the REST client
var witClient = VSS_Service.getCollectionClient(TFS_Wit_WebApi.WorkItemTrackingHttpClient);
// ...
console.log("obtiene cliente")
witClient.getWorkItems(/* some work item IDs */ [1,2,3,4], ["System.Title"]).then(
function(workItems:any) {
console.log(JSON.stringify(workItems));
});
});
But, It doesnt work when I try my first aproach, like this:
import RestClient = require("TFS/WorkItemTracking/RestClient");
I try to check my config files but dont know what to do, I have this in my package.json
"dependencies": {
"vss-web-extension-sdk": "^5.141.0"
},
and in my file tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["es5",
"es6",
"dom"],
"module": "amd",
"types": ["vss-web-extension-sdk"],
"moduleResolution": "node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}

ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.
Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons.
This is my configuration:
svelte.config.test.cjs
const preprocess = require('svelte-preprocess');
require('dotenv').config()
module.exports = {
preprocess: preprocess({
replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
{ return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
})
};
jest.config.cjs
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: './svelte.config.test.cjs'
}
],
"^.+\\.(js)$": "babel-jest",
'^.+\\.(ts)$': [require.resolve('jest-chain-transform'),
{ transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
]
},
testMatch: ["**/spec/**/*.js"],
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2020",
"lib": ["es2020", "DOM"],
"target": "es2019",
"importsNotUsedAsValues": "error",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"allowJs": true,
"checkJs": true,
"paths": {
"$/*": ["src/*"]
}
},
"include": [
"src/**/*.d.ts",
"src/**/*.js",
"src/**/*.ts",
"src/**/*.svelte",
"src/**/*.svelte-kit",
"./jest-setup.ts"
],
"exclude": ["node_modules"]
}
I have this information about an error in jest:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
^
SyntaxError: Unexpected token '<'
9 | import { createPopper } from '#popperjs/core';
10 | import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
| ^
I added to jest.config.test.cjs
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]
after moduleNameMapper but still it doesn't work.
Thanks for your help.
running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like
module.export = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }], '#babel/preset-typescript']
};
my jest.config.js
const config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
'^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(carbon-icons-svelte))',
'<rootDir>/node_modules/(?!(carbon-components-svelte))'
],
moduleFileExtensions: ['js', 'ts', 'svelte']
};
export default config;

Mocking a class in typescript with jest

I am trying to unit test (with Jest) my handler module that makes use of a summary class.
My original summary class looks like:
import DynamoDBClient from './ddbClient/DynamoDBClient'
import { DynamoDB } from 'aws-sdk'
import { iSummaryReader, iObsSummariesAttributes } from './Summary.d'
import { JSONAPIResource } from '../JSONAPIResponse'
export default class Summary {
reader: iSummaryReader
constructor(reader: iSummaryReader) {
this.reader = reader
}
getSummary = async (keyName: string, keyValue: string): Promise<JSONAPIResource<iObsSummariesAttributes>> => {
return new Promise<JSONAPIResource<iObsSummariesAttributes>>((resolve, reject) => {
const gettingItem = this.reader.getItem(keyName, keyValue)
console.log(gettingItem)
gettingItem.then((resp) => {
resolve(resp)
}).catch((err: Error) => {
reject(err.message)
})
})
}
}
In my handler module I import with import Summary from './lib/Summary'
(Note: same line is used in handler.test.ts
Inside the handler function
try {
const dynamodbObj: iSummaryReader = new DynamoDBClient(documentClient, someTable)
const summary = new Summary(dynamodbObj)
const data: JSONAPIResource<iObsSummariesAttributes> = await summary.getSummary('id', someID)
}
My results depend on my approach if try an automatic mock
jest.mock('./lib/Summary', () =>
{
return {
getSummary: jest.fn()
}
})
I get the error
TypeError: Summary_1.default is not a constructor
If I create a manual mock under lib/__mocks__/Summary.ts with jest.mock('./lib/Summary') it does work until I get the point
expect(Summary).toHaveBeenCalledTimes(1)
Where it complains about me not being able to do this on summary. I also am unable to access my method to test that they are being called this way.
Note: My hanlder is for a lambda function so I am unable to inject the class that way where I have successfully tested that I can mock an injected class.
EDIT
The tsconfig.json is:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declaration": false,
"target": "es2015",
"moduleResolution": "node",
"module": "commonjs",
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"alwaysStrict": true,
"lib": [
"dom",
"es2015.promise",
"es2017.object",
"es2016"
],
},
"include": [
"src/**/*.ts"
],
}
I do not know why this was failing, but I the following steps seem to work to fix it.
Change the class export from default
From
`export default class Summary {`
to
`class summary`
+ export = summary at the end
Use import = require to import it.
import Summary = require('./lib/Summary')
Those two changes allowed it to find the jest.mock.

Webpack / typescript require works but import doesn't

I'm trying to import a node_module into a TypeScript file. I'm using an adaptation of angular2-webpack-starter for my project structure.
import ace from 'brace';
In one of my files gives me
Cannot find module 'brace'.
But
var ace = require('brace');
Works fine. According to this issue I shouldn't be having any problems.
My webpack config file is copied from angular2-webpack-starter.
My tsconfig.json is as follows
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true
},
"files": [
"src/bootstrap.ts",
"src/vendor.ts",
"src/polyfills.ts"
],
"filesGlob": [
"./src/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Why would one work but not the other?
The answer is related to this issue. If a module doesn't have type data available (via a .d.ts file), the ES6 module syntax
import name from "module-name";
import * as name from "module-name";
import { member } from "module-name";
//etc
will not work and one must use the CommonJS alternative,
var name = require("module-name");