How to call function with Babel - node.js

I try call function with hapi-cron-job, but I get always error:
worker.js:54 execute: _cronsAntpool2['default'].account('btc'),
TypeError: Cannot read property 'account' of undefined
My worker.js has this code:
/**
* Imports
*/
import Hapi from 'hapi';
import schedule from 'hapi-cron-job';
import config from './config';
import Antpool from './crons/antpool';
/**
* Server setup
*/
const server = new Hapi.Server({
connections: {
router: {
stripTrailingSlash: true
}
}
});
server.connection({
host: config.app.workerhost,
port: config.app.workerport,
routes: {
cors: {
additionalHeaders: [
'Origin'
]
}
}
});
server.register({
register:require('hapi-cron-job'),
options:{
localTime: false, //GMT
jobs:[
{
name: "antpool - account - btc",
enabled: true,
immediate: true,
schedule: "every 24 hours",
execute: Antpool.account('btc'),
environments: ['development','production']
}
],
callback: callback
}
}, function(err){
if(err) { throw err; }
});
The function, which is called:
/**
* Imports
*/
import {signature} from '../core/antpool';
import log from '../core/logging';
import config from '../config';
import {sendLog as sendEmailLog, EmailTemplate} from '../core/email';
import {rethinkdb, Decorators as DBDecorators} from '../core/db';
import request from 'request';
const tables = {
AntpoolAccount: 'CronAntpoolAccount'
};
class Antpool {
#DBDecorators.table(tables.AntpoolAccount)
account(coin) {
var nonce = Date.now();
request.post({
url: config.antpool.baseUrl + '/api/account.htm',
json: true,
form: {
key: config.antpool.key,
nonce: nonce,
signature: signature(nonce),
coin: coin
}
}, function (err, httpResponse, body) {
if (err || httpResponse.statusCode != 201) {
log.error(err, '[CRON][Antpool][Account] Connection problem');
sendEmailLog(EmailTemplate.LOG, {
message: '[CRON][Antpool][Account] Connection problem'
});
return false;
}
var out = JSON.parse(body);
if (out.code != 0) {
log.error(err, '[CRON][Antpool][Account] Error response('+out.code+'): '+out.message);
sendEmailLog(EmailTemplate.LOG, {
message: '[CRON][Antpool][Account] Error response('+out.code+'): '+out.message
});
return false;
}
// Add to database
let obj = {
earn24: out.data.earn24Hours,
earnTot: out.data.earnTotal,
paidOut: out.data.paidOut,
balance: out.data.balance,
createdAt: new Date()
};
// Insert into database
let insert = this.table.insert(obj).run();
if(insert) {
return true;
} else {
return false;
}
});
}
}
/**
* Exports
*/
export {Antpool};
I am trying find the correct calling. But get always the error.
Seems problem with line execute: Antpool.account('btc'), in worker.js.
Any idea how to proper call function helps for me.
I am using Babel v. 5.8.38

Related

Issue with testing middleware in a nodejs express typescript project

I have been following https://github.com/goldbergyoni/nodebestpractices to learn more about nodejs best practices.
I have the following middleware that I implemented:
import { NextFunction, Request, Response } from "express";
import { BAD_REQUEST_ERROR_TYPES } from "../constants";
import { BadRequestError } from "./../error-handling";
const isAccountActive = (req: Request, res: Response, next: NextFunction) => {
if (req.session?.user?.isEmailVerified) {
next();
} else {
next(new BadRequestError(BAD_REQUEST_ERROR_TYPES.ACCOUNT_NOT_ACTIVE));
}
};
export default isAccountActive;
This is the test that I wrote for it:
describe("isAccountActive Middleware", () => {
describe("Recieving a request", () => {
test("When the request has a userUUID set in the session, it calls the next function without throwing a Bad Request Account Not Active error", async () => {
// Arrange
const req = {
method: "GET",
url: "/user/42",
session: {
user: {
userUUID: "some-string",
},
},
} as unknown as Request;
const res = jest.fn as unknown as Response;
const next = jest.fn;
// Act
await isAccountActive(req, res, next);
// Assert
expect(next).toBeCalledTimes(1);
expect(next).toBeCalledWith(
new BadRequestError(BAD_REQUEST_ERROR_TYPES.ACCOUNT_NOT_ACTIVE)
);
});
});
});
That is implementation number 3 for that test. I also tried using sinon, and node-mocks-http.
When I run the test command, I get the following error regardless of any implementation:
My app builds and runs fine; so I am not quite sure why jest would be throwing this error when the actuall server code itself is being compiled and run without any issues.
For reference, my config.ts:
import { isFullRedisURL } from "./helpers";
import { z } from "zod";
import { REDIS_URL_ERROR } from "./constants";
import { StartupError } from "./error-handling";
const input = {
environment: process.env.NODE_ENV,
basePort: process.env.BASE_PORT,
redisUrl: process.env.REDIS_URL,
redisPassword: process.env.REDIS_PASSWORD,
databaseUrl: process.env.DATABASE_URL,
sessionSecret: process.env.SESSION_SECRET,
};
const configSchema = z.object({
environment: z.string(),
basePort: z.coerce.number().positive().int(),
redisUrl: z
.string()
.refine((val) => isFullRedisURL(val), { message: REDIS_URL_ERROR }),
redisPassword: z.string(),
databaseUrl: z.string(),
sessionSecret: z.string().min(8),
});
let parsedInput;
try {
parsedInput = configSchema.parse(input);
} catch (e) {
throw new StartupError("Config validation error", e);
}
export const config = parsedInput;
export type Config = z.infer<typeof configSchema>;
my error-handling/error-handling-middleware.ts
import { COMMON_ERRORS, STATUS_CODES } from "../constants";
import { NextFunction, Request, Response } from "express";
import errorHandler from "./errorHandler";
import { config } from "../config";
const errorHandlingMiddleware = async (
// eslint-disable-next-line #typescript-eslint/no-explicit-any
error: any,
req: Request,
res: Response,
next: NextFunction
) => {
if (error && typeof error === "object") {
if (error.isTrusted === undefined || error.isTrusted === null) {
error.isTrusted = true; // Error during a specific request is usually not fatal and should not lead to process exit
}
}
errorHandler.handleError(error);
const { environment } = config;
const result = {
status: error?.httpStatus || STATUS_CODES.InternalServerError,
name: error?.name || COMMON_ERRORS.InternalServerError,
message: error?.message || "Sorry, something went wrong.",
details: error?.details,
stacktrace: environment === "development" ? error?.stacktrace : undefined,
};
res
.status(error?.httpStatus || STATUS_CODES.InternalServerError)
.send(result);
};
export default errorHandlingMiddleware;
the StartupError class:
import { FieldError } from "__shared/types";
import {
COMMON_ERRORS,
BAD_REQUEST_ERROR_MESSAGES,
BAD_REQUEST_ERROR_TYPES,
STATUS_CODES,
} from "../constants";
export class ApplicationError extends Error {
constructor(
public name: string,
public message: string,
public httpStatus: STATUS_CODES = STATUS_CODES.InternalServerError,
public isTrusted: boolean = true,
public isOperational: boolean = true,
public details?: FieldError[],
public stacktrace?: unknown
) {
super(message); // 'Error' breaks prototype chain here
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = name;
this.httpStatus = httpStatus;
this.isOperational = isOperational;
this.isTrusted = isTrusted;
this.details = details;
this.stacktrace = stacktrace;
Error.captureStackTrace(this, this.constructor);
}
}
export class BadRequestError extends ApplicationError {
constructor(type: keyof typeof BAD_REQUEST_ERROR_TYPES) {
super(
COMMON_ERRORS.BadRequestError,
BAD_REQUEST_ERROR_MESSAGES[type],
STATUS_CODES.BadRequest,
true,
true
);
}
}
export class StartupError extends ApplicationError {
constructor(reason: string, error: unknown) {
super(
COMMON_ERRORS.StartupError,
`Start up failed: (${reason}) `,
STATUS_CODES.InternalServerError,
false,
true,
undefined,
error
);
}
}

GraphQL Subscriptions is null using Express-GraphQL and graphql-subscriptions

I am using TypeScript and have Server and Client application. Below is the server code.
Server Code
import express, { Express } from "express";
import { graphqlHTTP } from "express-graphql";
import { buildSchema } from "type-graphql";
import { TaskResolver } from "./resolvers/task.resolver";
import { pgDatasource } from "./configs/db.config";
import { SeatBandingResolver } from "./resolvers/seatBanding.resolver";
import { GuestChatResolver } from "./resolvers/guestChat.resolver";
import { RateResolver } from "./resolvers/rate.resolver";
import { YearResolver } from "./resolvers/year.resolver";
import { ImplementationRateResolver } from "./resolvers/implementationRate.resolver";
import { UserResolver } from "./resolvers/user.resolver";
import { ReportResolver } from "./resolvers/report.resolver";
// Subscriptions
const ws = require("ws");
const { useServer } = require("graphql-ws/lib/use/ws");
const { execute, subscribe } = require("graphql");
const main = async () => {
const app: Express = express();
try {
//connect to db
await pgDatasource.initialize();
} catch (err) {
throw err;
}
//build gql schema
let schema = await buildSchema({
resolvers: [
SeatBandingResolver,
GuestChatResolver,
RateResolver,
YearResolver,
ImplementationRateResolver,
UserResolver,
],
validate: false,
// pubSub: new PubSub()
});
let schemaDoc = await buildSchema({
resolvers: [ReportResolver],
validate: false,
});
//ql schema for report
const docServer = graphqlHTTP((req, res) => {
return {
schema: schemaDoc,
graphiql: true,
context: {
req: req,
header: req.headers,
},
};
});
//setting a graphql server instance
const graphqServer = graphqlHTTP((req, res, graphQLParams) => {
return {
schema,
context: {
req: req,
header: req.headers,
},
graphiql: true,
};
});
app.use(cors());
//graphql endpoint : change it to backend
app.use("/graphql", graphqServer);
//for report : change name to google api
app.use("/doc", docServer);
//test route
app.get("/", (req, res) => {
res.json({
message: "Hello world",
});
});
let server = app.listen(3001, () => {
console.log("server started");
const wsServer = new ws.WebSocketServer({
host: "localhost",
// server,
path: "/graphql",
port: 3001,
});
useServer(
{
schema,
execute,
subscribe,
onConnect: (ctx) => {
console.log("Connect");
},
onSubscribe: (ctx, msg) => {
console.log("Subscribe");
},
onNext: (ctx, msg, args, result) => {
console.debug("Next");
},
onError: (ctx, msg, errors) => {
console.error("Error");
},
onComplete: (ctx, msg) => {
console.log("Complete");
},
},
wsServer
);
});
};
//starting a server
main()
.then(async (_) => {
// await addColumn()
})
.catch((err) => {
console.log(err);
});
Subscription Code at Client Side
import { Year } from "../entities/year.entity";
import { NewYear } from "../inputs/addYear.input";
import {
Arg,
Ctx,
Field,
Int,
Mutation,
ObjectType,
Query,
Resolver,
Root,
Subscription,
UseMiddleware,
} from "type-graphql";
import { Request } from "express";
import { Response } from "../helpers/response.helper";
import { Pagination } from "../inputs/pagination.input";
import { isAuth } from "../helpers/auth.helper";
import { PubSub, PubSubEngine } from "graphql-subscriptions";
const pubSub = new PubSub();
#ObjectType()
class MessagePayload {
#Field()
message: string;
}
#Resolver(() => Year)
export class YearResolver {
#Mutation(() => String)
async sendMessage(#Arg("message") message: string): Promise<string> {
console.log("in send subscription");
pubSub.publish("MESSAGE_NOTIFICATION", { message });
return message;
}
//calling the subscription
#Subscription(() => MessagePayload || null, {
topics: "MESSAGE_NOTIFICATION",
})
async receiveMessage(
#Root() root: MessagePayload
): Promise<MessagePayload | null> {
console.log("in publisher");
console.log(root, "in recieve message");
pubSub.asyncIterator("MESSAGE_NOTIFICATION");
return { message: "hello from the subscription" };
}
}
The issue I am facing here is Subscription is not working properly and the data is always null.
Can anyone help me to identify what I am missing here?
Thanks.
I'm not sure for 100% because your code descriptions are kinda confusing, but it looks like you should return pubSub.asyncIterator('MESSAGE_NOTIFICATION') in method receiveMessage. This method is called to start streaming messages to client at selected channel (MESSAGE_NOTIFICATION), not sending them. To send messages use pubsub. Of course you should change typing too.
You can find a similiar implementation here.

UnhandledPromiseRejectionWarning: Error: Not Found While sending email from Nestjs

I am trying to develop a mail sending module in my NestJs project. when I send the mail through my local machine it works fine. But when it goes to the server (digital-ocean droplet) it throws the following error and it does not send any email further. what is going on and fix this?
My code segment is below:
Auth controller
#Post('register')
async register(#Body() register: RegisterRequest) {
const res = await this.authService.register(register);
if (res instanceof Error) {
throw res;
}
return {
statusCode: 200,
message:
'Your account is registered successfully. Please check your email to verify your account',
};
}
Auth Service
async register(register: RegisterRequest): Promise<any> {
register.isRegister = true;
register.status = 0;
register.roleId = 5;
const user = await this.userService.save(register);
console.log('User Saved');
if (user instanceof User) {
if (register.isRegister) {
console.log('IS REGISTER');
// Generate Token
const resultsToken = await this.userTokenService.save(user.id, 1);
console.log('USER TOKEN SAVED');
if (resultsToken) {
this.mailService.sendUserConfirmation(user, resultsToken.token);
}
}
}
return user;
}
User Service
async save(register: RegisterRequest): Promise<User> {
try {
const token = generateToken(8);
const user = new User();
user.email = register.email;
user.firstName = register.firstName;
user.lastName = register.lastName;
user.password = hashPassword(register.password || token);
user.role = register.roleId;
user.phoneNumber = register.phoneNumber;
user.isActive = register.status;
const errors = await validate(user);
if (errors.length > 0) {
throw new ParameterMissingException(
errors[0].constraints[Object.keys(errors[0].constraints)[0]],
);
}
const existing = await this.findOneByEmail(register.email);
if (existing) {
throw new EntityFoundException('Email');
}
const registered = await this.userRepository.save(user);
return registered;
} catch (error) {
return error;
}
}
User Token service
async save(userId: number, type: number): Promise<UserToken> {
try {
const userToken = new UserToken();
userToken.user = userId;
userToken.type = type;
userToken.token = generateToken();
if (type === 2) {
userToken.expireIn = 15;
}
console.log('USER TOKEN SAVE');
return await this.userTokenRepository.save(userToken);
} catch (error) {
console.log('USER TOKEN ERROR');
return error;
}
}
Mail Service
sendUserConfirmation(user: any, token: string) {
const url = `${
this.configService.get<string>('REGISTER_CONFIRM_URL') + token
}`;
console.log('MAIL SERVICE ' + url);
this.mailerService
.sendMail({
to: user.email,
// from: '"Support Team" <support#example.com>', // override default from
subject: 'Greetings from CEWAS!',
template: join(__dirname, 'templates') + './register-confirmation',
context: {
url,
},
})
.then((r) => console.log(r))
.catch((err) => {
console.log('MAIL SERVICE ERROR');
console.log(err);
});
}
Mail Module and Config
import { MailerModule } from '#nestjs-modules/mailer';
import { HandlebarsAdapter } from '#nestjs-
modules/mailer/dist/adapters/handlebars.adapter';
import { Module } from '#nestjs/common';
import { MailService } from './mail.service';
import { join } from 'path';
#Module({
imports: [
MailerModule.forRoot({
transport: {
service: 'gmail',
secure: true,
auth: {
user: '********#gmail.com',
pass: '********',
},
},
defaults: {
from: '"<No Reply>" <*******#gmail.com>',
},
template: {
dir: join(__dirname, 'templates'),
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
providers: [MailService],
exports: [MailService],
})
export class MailModule {}
Hi try whit this configuration in your transport:
transport: {
host: 'smtp.gmail.com',
port: 465,
ignoreTLS: true,
secure: true,
auth: {
user: '********#gmail.com', //use the .env variable here for security
pass: '********'
},
}
and make sure you turned on access for less secure app
here the link: less secure app

Auth0 with Electron working in development but not when packaged

Im using Auth0 in an electron app to manage a log-in system. I referenced this tutorial here:
https://auth0.com/blog/securing-electron-applications-with-openid-connect-and-oauth-2/
to get started with using it.
Auth0 has been working great when I've been working in development but for some reason fails after I call "yarn package" to build the app. My electron app used electron-react-boilerplate (https://github.com/electron-react-boilerplate/electron-react-boilerplate).
Here are the important files:
// imports
...
import {
getAuthenticationURL,
refreshTokens,
loadTokens,
logout,
getLogOutUrl,
getProfile,
getResponse,
} from './services/authservice';
export default class AppUpdater {
constructor() {
...
}
}
let mainWindow: BrowserWindow | null = null;
if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install();
}
if (
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
) {
require('electron-debug')();
}
const installExtensions = async () => {
...
};
const createWindow = async () => {
console.log('now starting the main process');
if (
process.env.NODE_ENV === 'development' ||
process.env.DEBUG_PROD === 'true'
) {
await installExtensions();
}
const RESOURCES_PATH = app.isPackaged
? path.join(process.resourcesPath, 'assets')
: path.join(__dirname, '../assets');
const getAssetPath = (...paths: string[]): string => {
return path.join(RESOURCES_PATH, ...paths);
};
mainWindow = new BrowserWindow({
show: true,
width: 1024,
height: 728,
titleBarStyle: 'hidden', // add this line
frame: false,
//icon: getAssetPath('icon.png'),
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
const devtools = new BrowserWindow();
mainWindow.webContents.setDevToolsWebContents(devtools.webContents);
mainWindow.webContents.openDevTools({ mode: 'detach' });
};
/**
* Add event listeners...
*/
let win = null;
function createAuthWindow() {
destroyAuthWin();
win = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: false,
enableRemoteModule: false,
},
});
console.log(getAuthenticationURL());
win.loadURL(getAuthenticationURL());
const {
session: { webRequest },
} = win.webContents;
const filter = {
urls: [
'file:///callback*',
],
};
webRequest.onBeforeRequest(filter, async ({ url }) => {
console.log(url);
await loadTokens(url)
.then((res) => {
console.log(res);
})
.catch(console.log);
console.log('from web request');
createWindow();
return destroyAuthWin();
});
win.on('authenticated', () => {
console.log('WE HAVE AUTHENTICATED');
destroyAuthWin();
});
win.on('closed', () => {
win = null;
});
}
function destroyAuthWin() {
if (!win) return;
win.close();
win = null;
}
// logout logic: removed for simplicity
ipcMain.on('profileRequest', (event, arg) => {
//event.reply('profileResponse', getProfile());
event.returnValue = getProfile();
});
const showWindow = async () => {
try {
await refreshTokens();
return createWindow();
} catch (err) {
createAuthWindow();
}
};
this is my auth services file:
let accessToken = null;
let profile = {};
let refreshToken = null;
export function getAccessToken() {
return accessToken;
}
export function getProfile() {
return profile;
}
export function getAuthenticationURL() {
return (
'https://' +
auth0Domain +
'/authorize?' +
'scope=openid%20profile%20offline_access&' +
'response_type=code&' +
'client_id=' +
clientId +
'&' +
'redirect_uri=' +
redirectUri
);
}
export async function refreshTokens() {
const refreshToken = await keytar.getPassword(keytarService, keytarAccount);
if (refreshToken) {
const refreshOptions = {
method: 'POST',
url: `https://${auth0Domain}/oauth/token`,
headers: { 'content-type': 'application/json' },
data: {
grant_type: 'refresh_token',
client_id: clientId,
refresh_token: refreshToken,
},
};
try {
const response = await axios(refreshOptions);
res = response;
accessToken = response.data.access_token;
profile = jwtDecode(response.data.id_token);
} catch (error) {
await logout();
throw error;
}
} else {
throw new Error('No available refresh token.');
}
}
export async function loadTokens(callbackURL) {
console.log('loading tokens:');
console.log(callbackURL);
res = callbackURL;
const urlParts = url.parse(callbackURL, true);
const query = urlParts.query;
console.log(query);
const exchangeOptions = {
grant_type: 'authorization_code',
client_id: clientId,
code: query.code,
redirect_uri: redirectUri,
};
const options = {
method: 'POST',
url: `https://${auth0Domain}/oauth/token`,
headers: {
'content-type': 'application/json',
},
data: JSON.stringify(exchangeOptions),
};
try {
const response = await axios(options);
console.log('from token:');
console.log(response);
res = response;
accessToken = response.data.access_token;
profile = jwtDecode(response.data.id_token);
refreshToken = response.data.refresh_token;
console.log(getProfile());
if (refreshToken) {
await keytar.setPassword(keytarService, keytarAccount, refreshToken);
}
} catch (error) {
await logout();
throw error;
}
}
I have a file in my components folder called "Auth.jsx" which has a "get profile" methods which interacts with the main process to get the profile
const getProfile = () => {
return ipcRenderer.sendSync('profileRequest', true);
};
After I package the electron app, the getProfile method always returns null/undefined.
Here are the auth0 logs:
Auth0 Logs
It shows that there is a successful Login and Exchange.
Finally, here's my webpack file: "webpack.config.main.prod.babel"
/**
* Webpack config for production electron main process
*/
import path from 'path';
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import TerserPlugin from 'terser-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import baseConfig from './webpack.config.base';
import CheckNodeEnv from '../scripts/CheckNodeEnv';
import DeleteSourceMaps from '../scripts/DeleteSourceMaps';
import dotenv from 'dotenv';
CheckNodeEnv('production');
DeleteSourceMaps();
const devtoolsConfig =
process.env.DEBUG_PROD === 'true'
? {
devtool: 'source-map',
}
: {};
export default merge(baseConfig, {
...devtoolsConfig,
mode: 'production',
target: 'electron-main',
entry: './src/main.dev.ts',
output: {
path: path.join(__dirname, '../../'),
filename: './src/main.prod.js',
},
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
}),
],
},
plugins: [
new BundleAnalyzerPlugin({
analyzerMode:
process.env.OPEN_ANALYZER === 'true' ? 'server' : 'disabled',
openAnalyzer: process.env.OPEN_ANALYZER === 'true',
}),
new webpack.EnvironmentPlugin({
NODE_ENV: 'production',
DEBUG_PROD: true,
START_MINIMIZED: false,
/*
other environment variables, including auth0 domain name and clientID
*/
}),
],
/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false,
},
});
Im suspecting the problem might have something to do with webpack since it's only the packaged version of the application that doesn't work properly. Im not sure exactly what the problem is, whether is a problem in the code or if I need to specifically change something within my Auth0 dashboard. If you have any suggestions or any ideas on how to debug let me know!
I had the exact same issue! I fixed it by changing the import method for jwt-decode from require to import
import jwtDecode from 'jwt-decode'

Graphql Mysql - Get rows from a table in JSON Format

I'm working on Backend with TypeGraphQL and NodePostGres.
User will pass database id and table name. I need to send data in JSON Format.
I have tried below code but it doesn't return anything nor does it throw any error.
Service:
import { Service } from 'typedi'
import { Client } from 'pg'
import { databases } from './db'
import { Payload } from './models'
#Service()
export class PayloadService {
fetchPayload(id: number, tableName: string): Payload {
const databaseCredentials = databases.find((d) => d.id && +d.id === id)
if (!databaseCredentials) throw new Error('Invalid ID!')
const client = new Client({
host: databaseCredentials.host,
port: +(databaseCredentials.port || 5432),
user: databaseCredentials.username,
password: databaseCredentials.password,
database: databaseCredentials.database,
ssl: {
rejectUnauthorized: false,
},
})
console.log('before client')
client.query("select * from pg_tables where schemaname='public'", (err, res) => {
if (err) {
console.log(err.stack)
} else {
console.log(res.rows[0])
}
console.log(`callback`)
})
console.log('after client')
return {
id,
data: [],
}
}
}
Resolver:
import { Arg, Query, Resolver } from 'type-graphql'
import { Inject } from 'typedi'
import { Payload } from './models'
import { PayloadService } from './services'
#Resolver(Payload)
export class PayloadResolver {
#Inject()
private PayloadService: PayloadService
#Query((returns) => Payload)
payload(#Arg('databaseId') databaseId: number, #Arg('tableName') tableName: string) {
return this.PayloadService.fetchPayload(databaseId, tableName)
}
}

Resources