Can some provide an example how to obtain all the fields in giving class?
For example:
class A{
String aa;
String bb;
static String ss;
string simple(){
return 'simple';
}
getallMemberFields(){
// returun ["aa", "bb"]
}
}
If you are asking about reflection, here is an example of how to get not only variable and function names, but also some extra info about them
import 'dart:mirrors';
class A {
String aa;
String bb;
static String ss;
String simple() {
return 'simple';
}
getallMemberFields() {
// returun ["aa", "bb"]
}
}
void main() {
InstanceMirror instance_mirror = reflect(new A());
var class_mirror = instance_mirror.type;
for (var v in class_mirror.declarations.values) {
var name = MirrorSystem.getName(v.simpleName);
if (v is VariableMirror) {
print('Variable: $name');
print(
'Static: ${v.isStatic}, Private: ${v.isPrivate}, Final: ${v.isFinal}, Const: ${v.isConst}');
} else if (v is MethodMirror) {
print('Method: $name');
print(
'Static: ${v.isStatic}, Private: ${v.isPrivate}, Abstract: ${v.isAbstract}');
}
}
}
Prints:
Variable: aa
Static: false, Private: false, Final: false, Const: false
Variable: bb
Static: false, Private: false, Final: false, Const: false
Variable: ss
Static: true, Private: false, Final: false, Const: false
Method: simple
Static: false, Private: false, Abstract: false
Method: getallMemberFields
Static: false, Private: false, Abstract: false
Method: A
Static: false, Private: false, Abstract: false
Related
I want to create a polymorphic relation like in the diagram using sequalize-cli es6 format.
I have created this model using sequelize-cli
npx sequelize-cli model:generate --name Post --attributes name:string
npx sequelize-cli model:generate --name Video --attributes title:string
npx sequelize-cli model:generate --name Comment --attributes comments:text,comments_id:integer,comments_type:string
It generate following files
Model files:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Post extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Post.init({
name: DataTypes.STRING
}, {
sequelize,
modelName: 'Post',
});
return Post;
};
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Video extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Video.init({
title: DataTypes.STRING
}, {
sequelize,
modelName: 'Video',
});
return Video;
};
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Comment extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
Comment.init({
comments: DataTypes.TEXT,
comments_id: DataTypes.INTEGER,
comments_type: DataTypes.STRING
}, {
sequelize,
modelName: 'Comment',
});
return Comment;
};
Migration files:
'use strict';
/** #type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Posts', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Posts');
}
};
'use strict';
/** #type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Videos', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
title: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Videos');
}
};
'use strict';
/** #type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Comments', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
comments: {
type: Sequelize.TEXT
},
comments_id: {
type: Sequelize.INTEGER
},
comments_type: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('Comments');
}
};
Can anyone explain to me how to modify this files to make relationship like in the diagram. I am new to sequalize-cli orm .. Thank you.
I am trying to build a website. Using sequalize orm I will make my work much easier..
I think the below documentation will help U
URL: https://sequelize.org/docs/v6/advanced-association-concepts/eager-loading/
Answer:
Posts.hasMany(Comments)
Comments.belongsTo(Posts)
Videos.hasMany(Comments)
Comments.belongsTo(Videos)
How can I translate yup errors with next18-next since it should be server-side rendered?
Is it possible to use placeholders in next18-next translations strings?
It was pretty simple to solve this.
validate.ts:
export const setValidationTranslations = (t: TFunction) => {
const required = t("required");
const minString = t("min_string");
const maxString = t("max_string");
const emailValid = t("email_valid");
const minNumber = t("min_number");
const maxNumber = t("max_number");
setLocale({
mixed: {
required: required,
},
string: {
min: minString,
max: maxString,
email: emailValid,
},
number: {
min: minNumber,
max: maxNumber,
},
});
};
export const schema = () => {
return object().shape({
email: string().email().required(),
password: string().required().min(6),
});
};
Page.tsx:
import {
setValidationTranslations,
schema,
} from "./validate";
function Page() {
const { t } = useTranslation("common");
setValidationTranslations(t);
...
}
common.json with default yup texts:
{
"required": "${path} is a required field",
"email_valid": "${path} must be a valid email",
"min_string": "${path} must be at least ${min} characters",
"max_string": "${path} must be at most ${max} characters",
"min_number": "${path} must be greater than or equal to ${min}",
"max_number": "${path} must be less than or equal to ${max}"
}
This is my table:
#Entity('products')
export class Products {
#PrimaryGeneratedColumn()
#IsNumber()
public id: number;
#Column('decimal', {
precision: 20,
scale: 2,
transformer : {
to (value) {
return value ;
},
from (value) {
return parseFloat (value) ;
},
},
})
#IsNotEmpty()
price: number;
}
In my ormconfig file I have:
...
bigNumberStrings: false,
supportBigNumbers: true,
If I do:
return await this.repository.find();
Everything works correctly. The price field returns it as a decimal.
But if I use createQueryBuilder it brings it back as a string:
return await this.repository.createQueryBuilder("products")
.select([
'products.id AS id',
'products.price AS price'])
.getRawMany();
Please, could someone tell me how I can fix it?
i have a comments connection in a mutation, this is the query:
export default mutationFromQuery(graphql`
mutation AddBookMutation($input: AddBookInput! $count: Int $cursor: String ) {
addBook(input: $input) {
book {
__typename
cursor
node {
id
title
owner
createdAt
comments(first: $count, after: $cursor)
#connection(key: "BookComments_comments", filters: []) {
__typename
edges {
node {
id
}
}
}
}
}
}
}
`)
This is how i did my optimisticUpdater that don't work:
optimisticUpdater: (store) => {
const userProxy = store.get(viewerId)
const owner = userProxy.getValue('username')
const id = uuidv1();
const book = store.create(id, 'Book');
book.setValue(id, 'id');
book.setValue(bookTitle, 'title');
book.setValue(owner, 'owner');
book.setValue(Date.now(), 'createdAt');
const comments = store.create(uuidv1(), 'comments')
comments.setLinkedRecords([], 'edges')
const pageInfo = store.create(uuidv1(), 'pageInfo')
pageInfo.setValue(null, 'endCursor')
pageInfo.setValue(false, 'hasNextPage')
pageInfo.setValue(false, 'hasPreviousPage')
pageInfo.setValue(null, 'startCursor')
comments.setLinkedRecord(pageInfo, 'pageInfo')
book.setLinkedRecord(comments, 'comments')
const bookEdge = store.create(uuidv1(), 'BookEdge');
bookEdge.setLinkedRecord(book, 'node');
console.log('bookEdge ', bookEdge)
booksUpdater(userProxy, bookEdge);
},
The problem i have is that comments always ends up on undefined as you can see above i've already set it. I also did this but i am still not getting an optimistic UI:
optimisticResponse: {
addBook: {
book: {
__typename: 'BookEdge',
cursor: uuidv1(),
node: {
id: uuidv1(),
title: bookTitle,
owner: username,
createdAt: Date.now(),
comments: {
__typename: 'CommentConnection',
edges: [],
pageInfo: {
endCursor: null,
hasNextPage: false
}
}
}
}
}
},
App don't crash with optimisticResponse code but no optimistic UI effect, but with the optimisticUpdater it's crashing with comments being undefined, for now I am settling with my updater:
updater: (store) => {
const userProxy = store.get(viewerId)
const payload = store.getRootField('addBook');
booksUpdater(userProxy, payload.getLinkedRecord('book'));
},
since the comments is undefined I guess we cannot use this for optimistic effect:
const comments = store.create(uuidv1(), 'comments')
comments.setLinkedRecords([], 'edges')
book.setLinkedRecord(comments, 'comments')
on my Book, this is the query which has the comments fragment that is undefined on optimistic update with the code above:
export default createRefetchContainer(
BookItem,
{
book: graphql`
fragment BookItem_book on Book
#argumentDefinitions(
count: { type: "Int", defaultValue: 5 }
cursor: { type: "String", defaultValue: null }
) {
id
title
owner
createdAt
...BookComments_book
}
`
},
graphql`
query BookItemQuery($id: ID!, $count: Int, $cursor: String) {
book: node(id: $id) {
...BookItem_book #arguments(count: $count, cursor: $cursor)
}
}
`
);
and now the query for the comments component where it gets the book.comments.edges is undefined:
export default createPaginationContainer(
BookComments,
{
book: graphql`
fragment BookComments_book on Book
#argumentDefinitions(
count: { type: "Int", defaultValue: 3 }
cursor: { type: "String", defaultValue: null }
) {
id
title
comments(first: $count, after: $cursor)
#connection(key: "BookComments_comments", filters: []) {
__typename
edges {
node {
id
text
owner
createdAt
}
}
pageInfo {
startCursor
endCursor
hasPreviousPage
hasNextPage
}
}
}
`
},
{
direction: 'forward',
getConnectionFromProps: (props) => props.book && props.book.comments,
getFragmentVariables: (prevVars, totalCount) => ({
...prevVars,
count: totalCount
}),
getVariables: (props, { count, cursor }, _fragmentVariables) => ({
count,
cursor,
id: props.book.id
}),
query: graphql`
query BookCommentsQuery($id: ID!, $count: Int, $cursor: String) {
book: node(id: $id) {
...BookComments_book #arguments(count: $count, cursor: $cursor)
}
}
`
}
);
maybe this is an anti pattern? but i just wanted to have a optimistic effect for this
Some things are still not very clear to me about how those components and queries work, so I'll update this answer later. (I don't know if you want to return new book optimistically from node() query or add it to some list/connection of books)
Please check if I used correct type names (CommentConnection / CommentsConnection, etc)
optimisticUpdater: (store) => {
const userProxy = store.get(viewerId)
const owner = userProxy.getValue('username')
const commentsParams = { // must be same keys and values as in comments(first: $count, after: $cursor)
first: count,
after: cursor
}
// Create Book
const id = uuidv1();
const book = store.create(id, 'Book');
book.setValue(id, 'id');
book.setValue(bookTitle, 'title');
book.setValue(owner, 'owner');
book.setValue(Date.now(), 'createdAt');
// Create comments connection
const comments = store.create(uuidv1(), 'CommentConnection')
comments.setLinkedRecords([], 'edges')
// Create PageInfo
const pageInfo = store.create(uuidv1(), 'PageInfo')
pageInfo.setValue(null, 'endCursor')
pageInfo.setValue(false, 'hasNextPage')
pageInfo.setValue(false, 'hasPreviousPage')
pageInfo.setValue(null, 'startCursor')
// Link created records
comments.setLinkedRecord(pageInfo, 'pageInfo')
book.setLinkedRecord(comments, 'comments', commentsParams) // don't forget commentsParams with same values as are used in comments graphql query
// I'm not sure about this final part, because I don't really get how that app works, but if you want this book to show as optimistic response for `node(id: $id)`, you'll do something like this:
store.getRoot().setLinkedRecord(book, 'node', { id: id }) // same id as used in BookItemQuery
}
I looked at the dart:mirrors library, and I found ClassMirror. While I saw getField I didn't see access to all fields. I did see getters, though.
If I want to get all fields for a class, do I have to go through getters ?
Zdeslav Vojkovic's answer is a bit old.
This works for me, for Dart 1.1.3, as of March 2 2014.
import 'dart:mirrors';
class Test {
int a = 5;
static int s = 5;
final int _b = 6;
int get b => _b;
int get c => 0;
}
void main() {
Test t = new Test();
InstanceMirror instance_mirror = reflect(t);
var class_mirror = instance_mirror.type;
for (var v in class_mirror.declarations.values) {
var name = MirrorSystem.getName(v.simpleName);
if (v is VariableMirror) {
print("Variable: $name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}, C: ${v.isConst}");
} else if (v is MethodMirror) {
print("Method: $name => S: ${v.isStatic}, P: ${v.isPrivate}, A: ${v.isAbstract}");
}
}
}
Would output:
Variable: a => S: false, P: false, F: false, C: false
Variable: s => S: true, P: false, F: false, C: false
Variable: _b => S: false, P: true, F: true, C: false
Method: b => S: false, P: false, A: false
Method: c => S: false, P: false, A: false
Method: Test => S: false, P: false, A: false
No, you should go through ClassMirror.variables:
class Test {
int a = 5;
static int s = 5;
final int _b = 6;
int get b => _b;
int get c => 0;
}
void main() {
Test t = new Test();
InstanceMirror instance_mirror = reflect(t);
var class_mirror = instance_mirror.type;
for(var v in class_mirror.variables.values)
{
var name = MirrorSystem.getName(v.simpleName);
print("$name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}");
}
}
This will output:
_b => S: false, P: true, F: true
a => S: false, P: false, F: false
s => S: true, P: false, F: false
ClassMirror.getters would only return b and c.