Using RX with yeoman generator - javascript

I want to use RXJS with typescript yeoman generator, according to the docs inquirer which is the engine under yeoman support RXJS
https://github.com/SBoudrias/Inquirer.js/#reactive-interface
I use the following
export default class myGenerator extends Generator {
...
async prompting() {
const prompts = new Subject<Generator.Question>();
await this.prompt(prompts);
prompts.next({
name: "appName",
message: "app name: ",
type: "input",
default: this.props!.appName,
validate(input: string) {
const appName = validateAppName(input);
return !appName[1] ? appName[0] : true;
},
});
prompts.next({
type: "list",
name: "tech",
message: "Which type",
default: "CLI",
choices: [{ name: "CLI" }, { name: "CloudApp" }],
});
prompts.complete();
}
Now while running it I got error :
Error: You must provide a `name` parameter
at InputPrompt.throwParamError (/usr/local/lib/node_modules/yo/node_modules/inquirer/lib/prompts/base.js:73:11)
at new Prompt (/usr/local/lib/node_modules/yo/node_modules/inquirer/lib/prompts/base.js:33:12)
at new InputPrompt (/usr/local/lib/node_modules/yo/node_modules/inquirer/lib/prompts/input.js:11:1)
at PromptUI.fetchAnswer (/usr/local/lib/node_modules/yo/node_modules/inquirer/lib/ui/prompt.js:85:25)
at MergeMapSubscriber._tryNext (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/operators/mergeMap.js:69:27)
at MergeMapSubscriber._next (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/operators/mergeMap.js:59:18)
at MergeMapSubscriber.Subscriber.next (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/Subscriber.js:66:18)
at MergeMapSubscriber.notifyNext (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/operators/mergeMap.js:95:26)
at InnerSubscriber._next (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/InnerSubscriber.js:28:21)
at InnerSubscriber.Subscriber.next (/usr/local/lib/node_modules/yo/node_modules/rxjs/internal/Subscriber.js:66:18)
events.js:170
throw er; // Unhandled 'error' event
Im not sure where to put the name as all the prompts are providing the name property. , any idea ?
What I need is to create just two simple questions which will work with RXJS
How I can do that ?

Related

Javascript: (Discord.js) - TypeError: SlashCommandBuilder is not a constructor

On the line with asterisks (*) executing the code returns an error of TypeError: SlashCommandBuilder is not a constructor
//party command
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
*data: new SlashCommandBuilder()*
.setName('party')
.setDescription('Creates a party which others can join based on roles')
.addStringOption(option =>
option.setName('gamemode')
.setDescription('The name of the gamemode')
.setRequired(true)
.addChoices(
{ name: 'Hardcore', value: 'hc' },
{ name: 'Fallen', value: 'fn' },
{ name: 'Molten', value: 'mn' },
{ name: 'Normal', value: 'nm' },
{ name: 'Badlands II', value: 'bl' },
{ name: 'Polluted Wastelands II', value: 'pw' },
{ name: 'Pizza Party', value: 'pp' },
{ name: 'Other', value: 'ot' },
)),
async execute(interaction) {
await interaction.reply('You ran /party');
},
};
I am following a guide In the guide, scroll down to commands/ping.js. It appears to use SlashCommandBuilder as a constructor. I have expanded on it since and I'm confused about this. Thank you for your help.
Node.js v18.12.1
npm list
discord.js#12.5.3
dotenv#16.0.3
I have looked at this post which was made for the same reason, however the error was thrown due to a capitalization error of SlashCommandBuilder
The Discord.JS version you are using (v12) is simply outdated therefore it does not support recent features like slash commands, I recommend checking out this guide to learn the basic differences of V14.
If you are still struggling I recommend finding more resources online on the latest version.

Handle import dependency cycle in graphql

Let's say I declare two GraphQL types like this:
export const ChannelType = new GraphQLObjectType({
name: 'Channel',
fields: {
messages: { type: new GraphQLList(MessageType) },
},
});
export const MessageType = new GraphQLObjectType({
name: 'Message',
fields: {
channel: { type: ChannelType },
text: { type: GraphQLString },
},
});
The channel contains a list of messages, and the message needs to reference its owner channel.
The issue is that, if declared in a single file like this, the ChannelType does not know the Message type exists (because defined after).
And if I split them into separated files importing each other, I end up with an import dependency cycle.
I feel like this is a common issue but I can't get my head around it.
Any help?

Stripe Payments Add Payment Source / Card / Method using NodeJS / Vue

I am building a simple SaaS application with recurring payments using NodeJS with Express for the API and Vue for the UI. I have code written to add a customer and link a subscription and plan as well as a few other routines. We allow users to sign up without entering a payment method so now, I need to add a way for a user to add a payment method. I have been through so much documentation that my head is spinning and Stripe support (or lack thereof) has been no help.
I have tried everything from createSource, createToken, and createPaymentMethod in the UI and then submitted that to the API where I have tried using everything from stripeapi.customers.createSource to stripe.paymentMethods.create and nothing works. Everything returns an error about either something missing in the object or the object being incorrect. I have attempted to look at the payment intents API however, this seems like overkill to just simply add a card to a customer.
Here is my latest code.
UI : Create Element
this.stripe = await loadStripe('pk_test_');
let stripeElem = this.stripe.elements();
this.card = stripeElem.create('card', { hideIcon: true, hidePostalCode: false, style: { base: { color: '#363636', fontSize: '22px', fontSmoothing: 'antialiased' }}});
this.card.mount(this.$refs.card);
UI: Submit to API
await this.stripe.createSource(this.card, { type: 'card' } ).then((source) => {
this.$http.post(`/api/route`, source).then((response) => {
if (response.status === 200) {
} else {
}
}).catch(() => {
});
API
await stripeapi.customers.createSource(customer_id, { source: card });
This code produces this object:
{ source:
{ id: 'src_1HLFsEDfvqoM1TxYXmFvlcK9',
object: 'source',
amount: null,
card:
{ exp_month: 1,
exp_year: 2022,
last4: '4242',
country: 'US',
brand: 'Visa',
address_zip_check: 'unchecked',
cvc_check: 'unchecked',
funding: 'credit',
three_d_secure: 'optional',
name: null,
address_line1_check: null,
tokenization_method: null,
dynamic_last4: null },
client_secret: 'src_client_secret_VILuqM6ZikLzp9nMq4gizfN8',
created: 1598653002,
currency: null,
flow: 'none',
livemode: false,
metadata: {},
owner:
{ address: [Object],
email: null,
name: null,
phone: null,
verified_address: null,
verified_email: null,
verified_name: null,
verified_phone: null },
statement_descriptor: null,
status: 'chargeable',
type: 'card',
usage: 'reusable' } }
This code and object produce this error:
(node:352976) UnhandledPromiseRejectionWarning: Error: The source hash must include an 'object' key indicating what type of source to create.
at Function.generate (/data/api/node_modules/stripe/lib/Error.js:39:16)
at IncomingMessage.res.once (/data/api/docroot/node_modules/stripe/lib/StripeResource.js:190:33)
at Object.onceWrapper (events.js:286:20)
at IncomingMessage.emit (events.js:203:15)
at IncomingMessage.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
All I want to do is take an element, create a payment source/method (whatever it's called) and then associate that with a customer. Any help is appreciated. I have look at so many examples but nothing has worked for me. Everything seems to produce an error about the object or what not.
After more hours of development I finally figured it out! The API reference is severely lacking but this article here explains what to do: https://stripe.com/docs/payments/save-card-without-authentication
Essentially, you create and mount the element. Then, you use the createPaymentMethod in the UI and pass the card element to it. From there, you submit the paymentMethod.id string to your API and then use strip.paymentMethods.attach to attach it to a customer by passing the paymentMethod.id and the Stripe customer ID.
Front End HTML
<div ref="card" class="credit-card"></div>
Front End Create and Mount
this.stripe = await loadStripe('pk_test_YOURKEY');
let stripeElem = this.stripe.elements();
this.card = stripeElem.create('card', { hideIcon: true, hidePostalCode: false, style: { base: { color: '#363636', fontSize: '22px', fontSmoothing: 'antialiased' }}});
this.card.mount(this.$refs.card);
Front End Create Payment Method and Submit to Back End
await this.stripe.createPaymentMethod({ type: 'card', card: this.card }).then((method) => {
this.$http.post(`/users/billing/cards`, { id: method.paymentMethod.id }).then((response) => {
}).catch(() => {
});
}).catch(() => {
});
Please note: this code is NOT complete, it's just meant to give you an example for those that have struggled like I have.
The NodeJS error message reads:
The source hash must include an 'object' key indicating what type of source to create.
It can also be found here, but I'm not certain, if not this is a bogus error message. If this should indeed apply, it would be object: 'card' instead of object: 'source'; but I don't think so.
With Stripe there sometimes is more than one way to get something done:
The source should definitely be a client-side generated card token,
but your client-side doesn't have any code that would token-ize the card.
For reference, these would have to be combined:
https://stripe.com/docs/js/tokens_sources/create_token?type=cardElement
https://stripe.com/docs/api/cards/create

How do I properly create a connection in relay & graphql schema?

I am trying to create a pagination in relay & graphql in my schema. This is my code:
const GraphQLFriendByUser = new GraphQLObjectType({
name: 'FriendByUser',
fields: {
id: globalIdField('FriendByUser'),
_id: {
type: GraphQLString,
resolve: (root) => root._id,
},
email: {
type: GraphQLBoolean,
resolve: (root) => root.email,
},
fullName: {
type: GraphQLString,
resolve: (root) => {
return root.fullName;
},
},
},
interfaces: [nodeInterface],
});
const {
connectionType: FriendsByUserConnection,
edgeType: GraphQLFriendByUserEdge,
} = connectionDefinitions({
name: 'FriendByUser',
nodeType: GraphQLFriendByUser,
});
I created this similarly looking at sample in todo-modern, In my TodoListHome component, this is my graphql query:
friendsByUserContext( first: 200 ) #connection(key: "TodoListHome_friendsByUserContext") {
id
_id
fullName
email
}
there's no problem when I update the schema, but when I try to build, this is my error:
Invariant Violation: RelayParser: Unknown field id on type
FriendByUserConnection. Source: document TodoListHome_viewer file:
C:\Users\PE60\Desktop\socialnetworking-todoapp\js\components\TodoListHome.js.
The execution doesn't even reach on resolve, so I cannot log. but I believe the error is not from there. Help?
Since you're using graphql-js, you probably have graphiql hosted on your /graphql endpoint. That's a good place to debug queries and see the structure of your schema. There you'll see that the connection you're talking about has the field edges which has the field node which has the fields you're looking for.

Add object with relation to database using sequelize

I'm trying to add an object with a related object to the sequelize database but I can't figure out how to do it properly. I've read the documentation but I don't seem to have the methods on my objects they're using.
My model looks like this:
Client = db.define('Client', {
name: Seq.STRING,
street1: Seq.STRING,
street2: Seq.STRING,
zip: Seq.STRING(7),
city: Seq.STRING,
short: { type: Seq.STRING(10), unique: true, allowNull: true }
});
TrackedTime = db.define('TrackedTime', {
start: Seq.DATE,
end: Seq.DATE,
title: Seq.STRING,
description: Seq.TEXT
});
Client.hasMany(TrackedTime);
Client.sync();
TrackedTime.sync();
db.sync();
First I search for the client using arguments read from commandline args (this works):
Clients.findAll({ where: { name: arg }}).then(function (clients) {
startTimeTrack(clients, argv.t, argv.d, start);
});
And finally, the method that does not work as I've expected when I read the docs is this one:
function startTimeTrack(client, title, description, start) {
if (typeof client === 'undefined' || client === null)
throw "Please specify a client to track the time for!";
if (typeof title === 'undefined' || title === null)
throw "You need to specify a title!";
description = typeof description !== 'undefined' ? description : null;
start = typeof start !== 'undefined' ? start : new Date();
if (!(start instanceof Date))
throw "This is not a valid Date";
console.log('\nClient object:\n', JSON.stringify(client, null, 2));
TrackedTime.create({
start: start,
end: null,
title: title,
description: description
}).then(function (tt) {
console.log('\nTrackedTime object: \n' + JSON.stringify(tt, null, 2));
tt.setClient(client); // exception here!
});
}
The exception I get is this one:
Unhandled rejection TypeError: undefined is not a function
at startTimeTrack (C:\Users\admin\dev\tim\bin\cmd.js:255:5)
at C:\Users\admin\dev\tim\bin\cmd.js:221:6
at null.<anonymous> (C:\Users\admin\dev\tim\bin\cmd.js:285:4)
at tryCatcher (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\util.js:26:23)
at Promise._settlePromiseFromHandler (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\pr
omise.js:503:31)
at Promise._settlePromiseAt (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:
577:18)
at Promise._settlePromises (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:6
93:14)
at Async._drainQueue (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\async.js:123:16)
at Async._drainQueues (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebird\js\main\async.js:133:10)
at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\admin\dev\tim\node_modules\sequelize\node_modules\bluebir
d\js\main\async.js:15:14)
at processImmediate [as _immediateCallback] (timers.js:367:17)
I really don't know what I'm doing wrong here. The documentation did it like I did it here. I also tried multiple variations of that set-method (setClients, addClient).
How do I properly add related objects to the database using sequelize?
Edit:
This is the client object I'm receiving from the database:
Client object:
{
"id": 3,
"name": "Name Surname",
"street1": "Street 15",
"street2": "",
"zip": "12345",
"city": "City",
"short": "ms",
"createdAt": "2015-09-04T13:48:18.980Z",
"updatedAt": "2015-09-04T13:48:18.980Z"
}
Notice: I moved on with this small (and private) project and I'm just using node-sqlite3 to handle my 4 tables manually. If you, who landed here, have the same problem and one of the answers helped you, give me a hint and I'll accept it as answer.
FindAll will return array of clients, so if you want to return just one client you should use findOne.
Then according with Sequelize Associations docs , you could use createAssociation , in your case (not tested) :
function startTimeTrack(client, title, description, start) {
//....
//console.log(client.createTrackedTime) --> must return function
client.createTrackedTime({
start: start,
end: null,
title: title,
description: description
})
.then(function (tt) {
console.log(tt.get({plain:true}));
})
.catch(function (error){
console.log(error)
});
}

Categories