Discord bot: The base SlashCommand cannot be instantiated - heroku

On my computer it works fine, but when I try to host it on Heroku it gives this error
/app/node_modules/slash-create/lib/command.js:21
throw new Error('The base SlashCommand cannot be instantiated.');
^
Error: The base SlashCommand cannot be instantiated.
at new SlashCommand (/app/node_modules/slash-create/lib/command.js:21:19)
at new module.exports (/app/commands/back.js:5:9)
at SlashCreator.registerCommand (/app/node_modules/slash-create/lib/creator.js:64:23)
at SlashCreator.registerCommands (/app/node_modules/slash-create/lib/creator.js:105:18)
at SlashCreator.registerCommandsIn (/app/node_modules/slash-create/lib/creator.js:132:21)
at Object. (/app/index.js:39:6)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)

You are trying to register the base SlashCommand class as a command. You have to extend off of the class and add options to your command.
const { SlashCommand, CommandOptionType } = require('slash-create');
module.exports = class HelloCommand extends SlashCommand {
constructor(creator) {
super(creator, {
name: 'hello',
description: 'Says hello to you.',
options: [{
type: CommandOptionType.STRING,
name: 'food',
description: 'What food do you like?'
}]
});
this.filePath = __filename;
}
async run(ctx) {
return ctx.options.food ? `You like ${ctx.options.food}? Nice!` : `Hello, ${ctx.user.username}!`;
}
}
slash-create Example commands
slash-create template (with Heroku button)

Related

NestJS issue with circular dependency and undefined import

The past few days I've been studying NestJS + Graphql + Mongoose building a small project but started to find some issues due to database relationship and circular dependency. At the moment I'm able to query a patient with a list of previous hospitalizations (code first)
type Patient {
_id: ID!
name: String!
hospitalizations: [Hospitalization!]!
}
type Hospitalization {
_id: ID!
hospitalBed: Bed!
patient: Patient!
}
type PaginatedHospitalization {
totalCount: Int!
edges: [HospitalizationEdge!]
pageInfo: PageInfo!
}
type HospitalizationEdge {
cursor: String!
node: Hospitalization!
}
but I'm unable to update to update hospitalizations to be PaginatedHospitalization probably because of some circular dependency issue I'm unaware of. The error I'm getting on terminal when try to run the project is:
[8:35:19 AM] Starting compilation in watch mode...
[8:35:21 AM] Found 0 errors. Watching for file changes.
================ Hospitalization undefined
==== classRef undefined
/home/notroot/Documents/pessoal/_estudo/nest-graphql/src/common/entities/paginated.entity.ts:18
#ObjectType(`${classRef.name}Edge`)
^
TypeError: Cannot read properties of undefined (reading 'name')
at Paginated (/home/notroot/Documents/pessoal/_estudo/nest-graphql/src/common/entities/paginated.entity.ts:18:27)
at Object.<anonymous> (/home/notroot/Documents/pessoal/_estudo/nest-graphql/src/hospitalization/entities/paginated-hospitalization.entity.ts:9:56)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/home/notroot/Documents/pessoal/_estudo/nest-graphql/src/patient/entities/patient.entity.ts:7:1)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
These are my modules
#Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/nest-mongo'),
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
BedModule,
HospitalizationModule,
PatientModule,
],
})
export class AppModule {}
#Module({
imports: [
MongooseModule.forFeature([{ name: Patient.name, schema: PatientSchema }]),
forwardRef(() => HospitalizationModule),
],
providers: [PatientResolver, PatientService],
exports: [PatientService],
})
export class PatientModule {}
#Module({
imports: [
MongooseModule.forFeature([{ name: Bed.name, schema: BedSchema }]),
forwardRef(() => HospitalizationModule),
],
providers: [BedResolver, BedService],
exports: [BedService],
})
export class BedModule {}
#Module({
imports: [
MongooseModule.forFeature([
{ name: Hospitalization.name, schema: HospitalizationSchema },
]),
forwardRef(() => BedModule),
forwardRef(() => PatientModule),
],
providers: [HospitalizationResolver, HospitalizationService],
exports: [HospitalizationService],
})
export class HospitalizationModule {}
These are my Entities
#Schema()
#ObjectType()
export class Patient extends BaseEntity {
#Prop({ required: true })
#Field()
name: string;
#Prop({
type: [{ type: MongoSchema.Types.ObjectId, ref: 'Hospitalization' }],
})
// #Field(() => [Hospitalization], { defaultValue: [] })
#Field(() => PaginatedHospitalization)
hospitalizations?: Hospitalization[];
}
#Schema()
#ObjectType()
export class Bed extends BaseEntity {
#Prop({ required: true })
#Field()
name: string;
#Prop({
type: [{ type: MongoSchema.Types.ObjectId, ref: 'Hospitalization' }],
})
#Field(() => [Hospitalization], { defaultValue: [] })
// TODO: will be update to PaginatedHospitalization as well
hospitalizations?: Hospitalization[];
}
#Schema()
#ObjectType()
export class Hospitalization extends BaseEntity {
#Prop({ type: MongoSchema.Types.ObjectId, ref: 'Bed' })
#Field(() => Bed)
hospitalBed?: Bed;
#Prop({ type: MongoSchema.Types.ObjectId, ref: 'Patient' })
#Field(() => Patient)
patient?: Patient;
}
My paginated object is based on this generic pagination object from NestJS documentation
export function Paginated<T>(classRef: Type<T>): Type<IPaginatedType<T>> {
console.log('==== classRef', classRef);
#ObjectType(`${classRef.name}Edge`)
abstract class EdgeType {
#Field(() => String)
cursor: string;
#Field(() => classRef)
node: T;
}
#ObjectType({ isAbstract: true })
abstract class PaginatedType implements IPaginatedType<T> {
#Field(() => Int)
totalCount: number;
#Field(() => [EdgeType], { nullable: true })
edges: EdgeType[];
#Field(() => PageInfo)
pageInfo: PageInfo;
}
return PaginatedType as Type<IPaginatedType<T>>;
}
console.log('================ Hospitalization', Hospitalization);
#ObjectType()
export class PaginatedHospitalization extends Paginated(Hospitalization) {}
On the docs and examples I saw multiple cases of separate modules like PetModule, OwnerModule but the docs says that circular dependency should be avoided where possible. Is this a case that I should have a single module that have Patient, Bed and Hospitalization on the same module or some other solution?

How do I update an NFTs creator list?

I'mn trying to update a list of nfts to have a new secondary creator (the one with the 100% share). I don't think it's possible to update the first creator because I think the first creator is signed by the candy machine that created the nft? Anyway here's my code:
import { keypairIdentity, Metadata, Metaplex } from '#metaplex-foundation/js'
import { Connection, Keypair, PublicKey } from '#solana/web3.js'
import { program } from 'commander'
import { readFileSync, writeFileSync } from 'fs'
program
.command('update_creators')
.description('Updates the creator of all nfts')
.requiredOption(
'-i, --input-file <string>',
'Json file, list of NFT mint details'
)
.requiredOption(
'-o, --output-file <string>',
'Output file for NFT addresses that failed to update'
)
.requiredOption(
'-k, --keypair-file <path>',
`JSON file containing private key of token owner`,
'.cache/creator-keypair.json'
)
.option('-r, --rpc <string>', 'JSON rpc api url', defaultRpc)
.action(async ({ inputFile, outputFile, keypairFile, rpc }) => {
const connection = new Connection(rpc)
const metaplex = Metaplex.make(connection)
const keypairFileContents = readFileSync(keypairFile, 'utf-8')
const keypair = Keypair.fromSecretKey(
Buffer.from(JSON.parse(keypairFileContents))
)
metaplex.use(keypairIdentity(keypair))
const nftMintAddresses = JSON.parse(
readFileSync(inputFile, 'utf-8')
) as string[]
let nfts = (await metaplex
.nfts()
.findAllByMintList({
mints: nftMintAddresses.map(mint => new PublicKey(mint)),
})
.run()) as Metadata[]
const newCreator = new PublicKey(
'CUAwUE5N3TdHHHyPTHb3E5mpnpQFiRF6BcY8kEvJakfS'
)
const failedNfts: any[] = []
for (const nft of nfts) {
try {
console.dir(nft, { depth: null })
const newNft = await metaplex
.nfts()
.update({
nftOrSft: nft,
creators: [
nft.creators[0],
{
address: newCreator,
share: 100,
authority: keypair,
},
],
})
.run()
console.dir(newNft, { depth: null })
} catch (e) {
console.error(e)
failedNfts.push(nft)
process.exit()
}
}
writeFileSync(outputFile, JSON.stringify(failedNfts))
})
Note, the metaplex.use() keypair I'm using is the same wallet used to create the candy machine and has authority to update the nfts, but I keep getting the following error:
ParsedProgramError [MetaplexError]: TokenMetadataProgram > Incorrect account owner
>> Source: Program > TokenMetadataProgram [metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s]
>> Problem: The program [TokenMetadataProgram] at address [metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s] raised an error of code [57] that translates to "Incorrect account owner".
>> Solution: Check the error message provided by the program.
Caused By: IncorrectOwner: Incorrect account owner
at RpcClient.parseProgramError (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:302:9)
at RpcClient.sendTransaction (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:87:18)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RpcClient.sendAndConfirmTransaction (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:117:23)
at async TransactionBuilder.sendAndConfirm (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\TransactionBuilder.ts:189:22)
at async C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\Task.ts:82:23
at async Disposable.run (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\Disposable.ts:34:14)
at async Command.<anonymous> (C:\xampp\htdocs\sol-tools\src\cli.ts:263:24) {
key: 'metaplex.errors.program.parsed_program_error',
title: 'TokenMetadataProgram > Incorrect account owner',
problem: 'The program [TokenMetadataProgram] at address [metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s] raised an error of code [57] that translates to "Incorrect account owner".',
solution: 'Check the error message provided by the program.',
source: 'program',
sourceDetails: 'TokenMetadataProgram [metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s]',
cause: IncorrectOwner: Incorrect account owner
at Object.errorResolver (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\nftModule\plugin.ts:70:16)
at RpcClient.parseProgramError (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:299:35)
at RpcClient.sendTransaction (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:87:18)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RpcClient.sendAndConfirmTransaction (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\plugins\rpcModule\RpcClient.ts:117:23)
at async TransactionBuilder.sendAndConfirm (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\TransactionBuilder.ts:189:22)
at async C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\Task.ts:82:23
at async Disposable.run (C:\xampp\htdocs\sol-tools\node_modules\#metaplex-foundation\js\src\utils\Disposable.ts:34:14)
at async Command.<anonymous> (C:\xampp\htdocs\sol-tools\src\cli.ts:263:24) {
code: 57
},
logs: undefined,
program: {
name: 'TokenMetadataProgram',
address: PublicKey {
_bn: <BN: b7065b1e3d17c45389d527f6b04c3cd58b86c731aa0fdb549b6d1bc03f82946>
},
errorResolver: [Function: errorResolver],
gpaResolver: [Function: gpaResolver]
}
}
And here's one of the NFTs I'm trying to update:
https://solscan.io/token/3woKb11Ajs9VkzHhMNkiyX5za1bV3STBmSaDHoQgmBKp#metadata
Any help would be appreciated. Thanks!

Deploy NestJS to AWS Lambda

I have a REST API built using NestJS and I'm trying to deploy this to AWS Lambda.
I've created a file called serverless.ts in the src directory of my app -
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import serverlessExpress from '#vendia/serverless-express';
import { Handler, Callback, Context } from 'aws-lambda';
let server: Handler;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.init();
const expressApp = app.getHttpAdapter().getInstance();
return serverlessExpress({ app: expressApp });
}
bootstrap();
export const handler: Handler = async (
event: any,
context: Context,
callback: Callback,
) => {
server = server ?? (await bootstrap());
return server(event, context, callback);
};
Now, when I tried deploying this app/handler to AWS Lambda using Serverless framework, it failed a couple of times due to big package size (Lambda limits it to 250Mb).
The next option I had was to use docker and Elastic Container Registry (AWS ECR) to upload an image to Lambda.
Dockerfile -
FROM public.ecr.aws/lambda/nodejs:14
COPY package*.json ${LAMBDA_TASK_ROOT}
RUN npm install
COPY . ${LAMBDA_TASK_ROOT}
RUN npm run build
CMD [ "dist/serverless.handler" ]
I build this image and push to ECR Repository using the following commands -
aws ecr get-login-password --region region | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.region.amazonaws.com
docker tag e9ae3c220b23 aws_account_id.dkr.ecr.region.amazonaws.com/my-repository:tag
docker push aws_account_id.dkr.ecr.region.amazonaws.com/my-repository:tag
The push is successful now. Then I import this image to AWS Lambda and add a API Gateway Trigger to generate an HTTP endpoint.
When I try to access this endpoint, it says -
{ message: Internal server error }
When I view logs in Cloudwatch, this is what I see -
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'serverless'\nRequire stack:\n- /var/runtime/UserFunction.js\n- /var/runtime/Runtime.js\n- /var/runtime/index.js",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'serverless'",
"Require stack:",
"- /var/runtime/UserFunction.js",
"- /var/runtime/Runtime.js",
"- /var/runtime/index.js",
" at _loadUserApp (/var/runtime/UserFunction.js:221:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:279:17)",
" at Object. (/var/runtime/index.js:43:34)",
" at Module._compile (internal/modules/cjs/loader.js:1085:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
" at Module.load (internal/modules/cjs/loader.js:950:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:790:12)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)",
" at internal/main/run_main_module.js:17:47"
]
}
I am unable to figure out the root cause and a fix for this issue. How do I resolve this?

Schematic "my-comp" cannot resolve the factory

I'm following this book: https://github.com/manfredsteyer/schematics-sample
When I execute my schematics
schematics .:my-comp
I get the following error:
An error occured:
Error: Schematic "my-comp" cannot resolve the factory.
at NodeModulesEngineHost.createSchematicDescription (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/node_modules/#angular-devkit/schematics/tools/file-system-engine-host-base.js:174:19)
at SchematicEngine.createSchematic (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/node_modules/#angular-devkit/schematics/src/engine/engine.js:219:38)
at CollectionImpl.createSchematic (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/node_modules/#angular-devkit/schematics/src/engine/engine.js:69:29)
at NodeWorkflow.execute (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/node_modules/#angular-devkit/schematics/src/workflow/base.js:99:38)
at main (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/bin/schematics.js:202:24)
at Object.<anonymous> (/home/.../.npm-global/lib/node_modules/#angular-devkit/schematics-cli/bin/schematics.js:293:5)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
This is part of my factory:
export default function myComp(options: IFlexComponentOptions): Rule {
return (host: Tree, context: SchematicContext) => {
console.log("options before sanatize", options);
...
return rule(host, context);
};
}
my collectyion.json
{
"$schema": "../node_modules/#angular-devkit/schematics/collection-schema.json",
"schematics": {
"my-comp": {
"description": "This schematics generate an Angular Component on the current module or in an specified one",
"factory": "./my-comp/index#myComp"
}
}
}
I had the same problem, from export default function myComp remove the default. And it should work. I follow the same book. Lots of incompatibilities.
For those who doesn't use default and has the same issue, please check the hash name versus the function name in the index file.

GraphQL: Error: Schema query must be Object Type but got: [object Object]

I'm currently trying to inherit schemas for a rootQuery in order to get more modularity. The setup currently looks as follows:
invoiceSchema.js
import {
GraphQLObjectType,
GraphQLInt,
} from 'graphql';
export default new GraphQLObjectType({
name: 'Invoice',
description: 'A monthly billing invoice for an organization',
fields: () => ({
amountDue: {
type: GraphQLInt,
description: 'The amount the card will be charged (total + startingBalance with a min value of 0)'
},
})
});
rootQuery.js
import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLList,
GraphQLID
} from 'graphql';
import Invoice from './invoiceSchema';
export default {
Invoice: {
type: Invoice,
resolve(parentValue, args){
return 'Hello world';
}
}
};
schema.js
import query from './rootQuery';
import {GraphQLSchema} from 'graphql';
export default new GraphQLSchema({query});
When trying to do the following error and hoped for some help and insight, as what I'm exporting in invoiceSchema.js is clearly an ObjectType and not an object Object.
C:\project\node_modules\graphql\jsutils\invariant.js:19
throw new Error(message);
^
Error: Schema query must be Object Type but got: [object Object].
at invariant (C:\project\node_modules\graphql\jsutils\invariant.js:19:11)
at new GraphQLSchema (C:\project\node_modules\graphql\type\schema.js:72:88)
at Object.<anonymous> (C:/project/api/schema/schema.js:6:16)
at Module._compile (module.js:573:30)
at loader (C:\project\node_modules\babel-register\lib\node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (C:\project\node_modules\babel-register\lib\node.js:154:7)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Module.require (module.js:517:17)
[nodemon] app crashed - waiting for file changes before starting...
Actually got the idea from here and I'm wondering why it doesn't work...
Your root query needs to be an instance of GraphQLObjectType, however, rootQuery.js is exporting a plain Object instead. You'll need to change your export to something like this:
export default new GraphQLObjectType({
name: 'RootQuery',
fields: () => ({
invoice: {
type: Invoice,
resolve(parentValue, args){
return 'Hello world';
}
}
})
};
Note: it's common practice to keep all field names, including query and mutation names, in camelCase and use PascalCase for type names, to help distinguish between the two.
Also, if you are modularizing your schema, you may find it helpful to utilize graphql-tools for generating your schema instead. IMO, it makes your schema more readable and helps avoid some of the more common pitfalls you may face when modularizing a schema. The docs have a great example of how to modularize your schema with makeExecutableSchema here.

Resources