sequelize cli creating a polymorphic one to many and many to many relation - polymorphic-associations

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)

Related

Convert API Gateway Cloudformation template to Swagger file

There is an existing API described in a Coludformation template. Now I want to document the API using Swagger. Is there a way to parse the Cloudformation template to create the swagger.yaml specification file? I would like to avoid writing the API a second time, if possible.
Note: I am aware that you can define your API using Swagger, then import the API configuration in your Cloudformation template. This is not what I need. The Cloudformation already exists and will not be changed. Hence, I need the opposite: a Swagger configuration file based on an existing Cloudformation template.
There is no way to convert the template to a swagger file that I know about. But if you are looking for a way to keep service-spec in one place only (template) and you have it deployed, you can take swagger or OAS file from the stage (so to do it you must have a stage as well) in two ways at least:
By Web console. Use Amazon API Gateway->
APIs->Your API->Stages>Your Stage -> Export tab. See the picture: exporting Swagger or OAS as a file by Web console
aws apigateway get-export ... Here is an example:
aws apigateway get-export --rest-api-id ${API_ID} --stage-name ${STAGE_NAME} --export-type swagger swagger.json
I just made this, it is not setup for perfect plug/play, but will give you an idea what you need to adjust to get it working (also need to make sure you CF template is setup so it has the needed info, on mine I had to add some missing requestParams I was missing, also use this site to test your results from this code to see it works with swagger):
const yaml = require('js-yaml');
const fs = require('fs');
// Get document, or throw exception on error
try {
// loads file from local
const inputStr = fs.readFileSync('../template.yaml', { encoding: 'UTF-8' });
// creating a schema to handle custom tags (cloud formation) which then js-yaml can handle when parsing
const CF_SCHEMA = yaml.DEFAULT_SCHEMA.extend([
new yaml.Type('!ImportValue', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::ImportValue': data };
},
}),
new yaml.Type('!Ref', {
kind: 'scalar',
construct: function (data) {
return { Ref: data };
},
}),
new yaml.Type('!Equals', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Equals': data };
},
}),
new yaml.Type('!Not', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Not': data };
},
}),
new yaml.Type('!Sub', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::Sub': data };
},
}),
new yaml.Type('!If', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::If': data };
},
}),
new yaml.Type('!Join', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Join': data };
},
}),
new yaml.Type('!Select', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::Select': data };
},
}),
new yaml.Type('!FindInMap', {
kind: 'sequence',
construct: function (data) {
return { 'Fn::FindInMap': data };
},
}),
new yaml.Type('!GetAtt', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::GetAtt': data };
},
}),
new yaml.Type('!GetAZs', {
kind: 'scalar',
construct: function (data) {
return { 'Fn::GetAZs': data };
},
}),
new yaml.Type('!Base64', {
kind: 'mapping',
construct: function (data) {
return { 'Fn::Base64': data };
},
}),
]);
const input = yaml.load(inputStr, { schema: CF_SCHEMA });
// now that we have our AWS yaml copied and formatted into an object, lets pluck what we need to match up with the swagger.yaml format
const rawResources = input.Resources;
let guts = [];
// if an object does not contain a properties.path object then we need to remove it as a possible api to map for swagger
for (let i in rawResources) {
if (rawResources[i].Properties.Events) {
for (let key in rawResources[i].Properties.Events) {
// console.log(i, rawResources[i]);
if (rawResources[i].Properties.Events[key].Properties.Path) {
let tempResource = rawResources[i].Properties.Events[key].Properties;
tempResource.Name = key;
guts.push(tempResource);
}
}
}
} // console.log(guts);
const defaultResponses = {
'200': {
description: 'successful operation',
},
'400': {
description: 'Invalid ID supplied',
},
};
const formattedGuts = guts.map(function (x) {
if (x.RequestParameters) {
if (
Object.keys(x.RequestParameters[0])[0].includes('path') &&
x.RequestParameters.length > 1
) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
{
name: Object.keys(x.RequestParameters[1])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[1])[0].Required,
},
],
responses: defaultResponses,
},
},
};
} else if (Object.keys(x.RequestParameters[0])[0].includes('path')) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split('method.request.path.')[1],
in: 'path',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
],
responses: defaultResponses,
},
},
};
} else if (Object.keys(x.RequestParameters[0])[0].includes('querystring')) {
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
parameters: [
{
name: Object.keys(x.RequestParameters[0])[0].split(
'method.request.querystring.'
)[1],
in: 'query',
type: 'string',
required: Object.values(x.RequestParameters[0])[0].Required,
},
],
responses: defaultResponses,
},
},
};
}
}
return {
[x.Path]: {
[x.Method]: {
tags: [x.RestApiId.Ref],
summary: x.Name,
responses: defaultResponses,
},
},
};
});
const swaggerYaml = yaml.dump(
{
swagger: '2.0',
info: {
description: '',
version: '1.0.0',
title: '',
},
paths: Object.assign({}, ...formattedGuts),
},
{ noRefs: true }
); // need to keep noRefs as true, otherwise you will see "*ref_0" instead of the response obj
// console.log(swaggerYaml);
fs.writeFile('../swagger.yaml', swaggerYaml, 'utf8', function (err) {
if (err) return console.log(err);
});
} catch (e) {
console.log(e);
console.log('error above');
}

How to access Customer table's data in nopcommerce

I want to show Customer table's data of nopcommerce in admin page.
i did write a plugin for that and receive data in controller but in view i have a problem and show me error happened message.
here is my controller code:
public class UserDetailsController : BasePluginController
{
private ICustomerService _UserDetail;
public UserDetailsController(ICustomerService UserDetail)
{
_UserDetail = UserDetail;
}
public ActionResult Manage()
{
return View();
}
[HttpPost]
public ActionResult GetUsers(DataSourceRequest userDetail)
{
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data = details,
Total = details.Count
};
return Json(gridModel);
}
}
And this is my view code:
#{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<script>
$(document).ready(function() {
$("#user-details").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetUsers", "UserDetails"))",
type: "POST",
dataType: "json",
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
}
},
requestEnd: function(e) {
if (e.type == "update") {
this.read();
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info:false
},
editable: {
confirmation: true,
mode: "inline"
},
scrollable: false,
columns: [
{
field: "Email",
title: "User Name",
width: 200
},
{
command: [
{
name: "edit",
text: "#T("Admin.Common.Edit")"
}, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
});
</script>
<div id="user-details"></div>
can anybody help me?
Change your GetUsers method on this way:
var details = _UserDetail.GetAllCustomers();
var gridModel = new DataSourceResult
{
Data=details.Select(x=>
{
return new UserDetail()
{
Email= x.Email
};
}),
Total = details.Count(),
};
return Json(gridModel);

Grid Not populating in kendoGrid

I am using MVC 4 and kendo UI for grid population. But the grid is not populating correctly.
this is my View :
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data;
var element = $("#grid4").kendoGrid({
dataSource: {
data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
}
});
</script>
Conroller ;
[HttpGet]
public ActionResult Employee_Read([DataSourceRequest]DataSourceRequest request)
{
using (var emp = new MockProjectAkarshEntities1())
{
IQueryable<tbl_UserDetails> userDetails = emp.tbl_UserDetails;
DataSourceResult result = userDetails.ToDataSourceResult(request);
return Json(result,JsonRequestBehavior.AllowGet);
}
In the output I am getting something like "[object][object]" and no of rows in the table returned from database.the skeleton of grid is coming but not the data. I am new to MVC and kendo. Please help me out.
The data you received should be started with {"Data": So simply change your code from var dataloc = data; to var dataloc = data.Data; just confirm it by visiting UserSummary/Employee_Read.
You can also set the dataSource later on like this (if you prefer at some stage)
<script type="text/javascript">
$.ajax({
url: '#Url.Action("Employee_Read", "UserSummary")',
type: 'GET',
dataType: "json",
Async: true,
success: function (data, textStatus, xhr) {
var dataloc = data.Data;
var element = $("#grid4").kendoGrid({
dataSource: {
// data: dataloc,
schema: {
model: {
fields: {
userDetailsId: { type: "number", editable: false },
name: { type: "string", editable: false },
roleId: { type: "string", editable: false },
emailId: { type: "string", editable: false }
}
}
}
}
});
// create data source using the data received
var ds = new kendo.data.DataSource({
data: dataloc
});
$('#grid4').data('kendoGrid').setDataSource(ds);
}
});
</script>

Jaydata web api with OData provider -- provider fallback failed error

I'm developing an application with jaydata, OData and web api. Source code is given below:
$(document).ready(function () {
$data.Entity.extend('$org.types.Student', {
Name: { type: 'Edm.String', nullable: false, required: true, maxLength: 40 },
Id: { key: true, type: 'Edm.Int32', nullable: false, computed: false, required: true },
Gender: { type: 'Edm.String', nullable: false, required: true, maxLength: 40 },
Age: { type: 'Edm.Int32', nullable: false, required: true, maxLength: 40 }
});
$data.EntityContext.extend("$org.types.OrgContext", {
Students: { type: $data.EntitySet, elementType: $org.types.Student },
});
var context = new $org.types.OrgContext({ name: 'OData', oDataServiceHost: '/api/students' });
context.onReady(function () {
console.log('context initialized.');
});
});
In above JavaScript code, I defined an entity named Student. In context.onReady() method, I'm getting the following error:
Provider fallback failed! jaydata.min.js:100
Any idea, how I could get rid of this error??
As per suggested solution, I tried to change the key from required to computed. But sadly its still giving the same error. Modified code is given below.
$(document).ready(function () {
$data.Entity.extend('Student', {
Id: { key: true, type: 'int', computed: true },
Name: { type: 'string', required: true}
});
$data.EntityContext.extend("$org.types.OrgContext", {
Students: { type: $data.EntitySet, elementType: Student },
});
var context = new $org.types.OrgContext({
name: 'OData',
oDataServiceHost: '/api/students'
});
context.onReady(function () {
console.log('context initialized.');
});
});
I thinks the issue is with Odata provider because I tried the same code with indexdb provider and its working properly.
The issue is caused by the value oDataServiceHost parameter. You should configure it with the service host, not with a particular collection of the service. I don't know if the provider name is case-sensitive or not, but 'oData' is 100% sure.
For WebAPI + OData endpoints the configuration should look like this:
var context = new $org.types.OrgContext({
name: 'oData',
oDataServiceHost: '/odata'
});

Kendo UI Grid Update button not firing

I am developing a KendoUI Grid with Inline editable option in javascript and can't make Update button to fire click event and post the data to server side update event. Clicking on Update button won't even update the grid on client.
Hope someone can help me point out what I am doing wrong here.
This is not a duplicate to this as I have tired the jfiddle link in the answer and it is not working too.
kendo UI grid update function wont fire
<div id="grid"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/GetPupilsAsJson",
dataType: 'json'
},
update: {
url: "Home/UpdatePupils",
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
$('#grid').kendoGrid({
dataSource: dataSource,
editable: "inline",
pageable: true,
columns: [{
field: "Id",
title: "Id",
width: 150,
hidden: true
}, {
field: "Firstname",
title: "Firstname",
width: 150
}, {
field: "Lastname",
title: "Lastname",
width: 150
}, {
field: "DateOfBirth",
title: "DateOfBirth",
width: 150
}, {
field: "Class",
title: "Class",
width: 150
}, {
field: "Year",
title: "Year",
width: 150
},
{
command: ["edit"],
width: 150
}]
});
});
</script>
}
HomeController
public ActionResult GetPupilsAsJson()
{
return Json(GetPupils(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public void UpdatePupils(Pupil p)
{
//never reach here
}
I don't know why but fixed it by putting schema information.
schema: {
model: {
id: "Id",
fields: {
Firstname: { editable: true, validation: { required: true } },
Lastname: { validation: { required: true } },
DateOfBirth: { validation: { required: true } },
Class: { validation: { required: true } },
Year: { validation: { required: true } }
}
}
}
Use #Url.Action("GetPupilsAsJson", "Home")' so no need to pass base url in your update action like this BASEURL+ "Home/GetPupilsAsJson".
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',
dataType: 'json'
},
update: {
url:'#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
use parameter map to pass model values
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',,
dataType: 'json'
},
update: {
url: '#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 5,
autoSync: true
});
Call Controller with parameterMap
public JsonResult UpdatePupils(string models)
{
return Json(..);
}
Is any of your cell text has HTML tags like < or >, remove them and click on update. The update event will fire.

Resources