Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Main tweets #379

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
const express = require('express')
const helpers = require('./_helpers');
const express = require("express");
const handlebarsHelpers = require("./helpers/handlebars-helpers");
const handlebars = require("express-handlebars");
const session = require("express-session");
const routes = require("./routes");

const app = express()
const port = 3000
const app = express();
const port = 3000;
const SESSION_SECRET = "secret";

// use helpers.getUser(req) to replace req.user
// use helpers.ensureAuthenticated(req) to replace req.isAuthenticated()

app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.set("view engine", "hbs");
app.engine("hbs", handlebars({ extname: ".hbs", helpers: handlebarsHelpers }));
app.use(express.urlencoded({ extended: true }));
app.use(
session({ secret: SESSION_SECRET, resave: false, saveUninitialized: false })
);
app.use("/", express.static("public"));

module.exports = app
app.use(routes);
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

module.exports = app;
30 changes: 30 additions & 0 deletions controllers/tweets-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const { Tweet, User } = require("../models");

const tweetsController = {
getTweets: async (req, res, next) => {
try {
const users = await User.findAll({ raw: true });
const tenRandomUsers = [];
for (let i = 0; i < 8; i++) {
const index = Math.floor(Math.random() * users.length);
tenRandomUsers.push(users[index]);
}
res.render("tweets", { recommend: tenRandomUsers });
} catch (err) {
console.log(err);
}
},
postTweet: (req, res, next) => {
const { text } = req.body;
console.log(text);
if (!text) throw new Error("Content is required!");
return Tweet.create({
UserId: 1, //待登入功能好,存入req.user
description: text,
})
.then(() => res.redirect("/tweets"))
.catch((err) => console.log(err));
},
};

module.exports = tweetsController;
25 changes: 25 additions & 0 deletions controllers/user-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const { Tweet, User, Followship } = require("../models");

const userController = {
postFollow: async (req, res, next) => {
try{
const { followingUserId } = req.params;
const currentUserId = req.user.id;
const user = await User.findByPk(followingUserId);
const followship = await Followship.findOne({
where: { followerId: currentUserId, followingId: followingUserId },
});
if (!user) throw new Error("User didn't exist");
if (followship) throw new Error("You are already following this user!");
await Followship.create({
followerId: currentUserId,
followingId: followingUserId,
});
res.redirect("back");
} catch(err) {
console.log(err)
}
},
};

module.exports = userController;
10 changes: 10 additions & 0 deletions helpers/handlebars-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// const dayjs = require("dayjs");
// const relativeTime = require("dayjs/plugin/relativeTime");
// dayjs.extend(relativeTime);
module.exports = {
// currentYear: () => dayjs().year(),
// relativeTimeFromNow: (a) => dayjs(a).fromNow(),
ifCond: function (a, b, options) {
return a === b ? options.fn(this) : options.inverse(this);
},
};
17 changes: 12 additions & 5 deletions migrations/20190115071421-create-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,31 @@ module.exports = {
primaryKey: true,
type: Sequelize.INTEGER
},
email: {
account: {
type: Sequelize.STRING
},
password: {
name: {
type: Sequelize.STRING
},
name: {
email: {
type: Sequelize.STRING
},
avatar: {
password: {
type: Sequelize.STRING
},
introduction: {
type: Sequelize.TEXT
},
role: {
avatar: {
type: Sequelize.STRING
},
background: {
type: Sequelize.STRING
},
role: {
type: Sequelize.STRING,
defaultValue: 'user'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
Expand Down
30 changes: 24 additions & 6 deletions models/followship.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,26 @@
'use strict';
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
const Followship = sequelize.define('Followship', {
}, {});
Followship.associate = function(models) {
class Followship 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
}
};
return Followship;
};
Followship.init({
followerId: DataTypes.INTEGER,
followingId: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Followship',
tableName: 'Followships'
// underscored: true
})
return Followship
}
26 changes: 21 additions & 5 deletions models/like.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
'use strict';
const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
const Like = sequelize.define('Like', {
}, {});
Like.associate = function(models) {
};
class Like extends Model {
static associate(models) {
Like.belongsTo(models.User, { foreignKey: 'UserId' });
Like.belongsTo(models.Tweet, { foreignKey: 'TweetId' });
}
}
Like.init(
{
UserId: DataTypes.INTEGER,
TweetId: DataTypes.INTEGER
},
{
sequelize,
modelName: 'Like',
tableName: 'Likes',
}
);

return Like;
};
};
32 changes: 26 additions & 6 deletions models/reply.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
'use strict';
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
const Reply = sequelize.define('Reply', {
}, {});
Reply.associate = function(models) {
class Reply 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) {
Reply.belongsTo(models.Tweet, { foreignKey: 'TweetId' })
Reply.belongsTo(models.User, { foreignKey: 'UserId' })
}
};
return Reply;
};
Reply.init({
comment: DataTypes.TEXT,
userId: DataTypes.INTEGER,
tweetId: DataTypes.INTEGER
}, {
sequelize,
modelName: 'Reply',
tableName: 'Replies'
// underscored: true
})
return Reply
}
32 changes: 26 additions & 6 deletions models/tweet.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
'use strict';
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
const Tweet = sequelize.define('Tweet', {
}, {});
Tweet.associate = function(models) {
class Tweet 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) {
Tweet.belongsTo(models.User, { foreignKey: 'UserId' })
Tweet.hasMany(models.Reply, { foreignKey: 'TweetId' })
Tweet.hasMany(models.Like, { foreignKey: 'TweetId' })

}
};
return Tweet;
};
Tweet.init({
description: DataTypes.TEXT
}, {
sequelize,
modelName: 'Tweet',
tableName: 'Tweets'
// underscored: true
})
return Tweet
}
49 changes: 43 additions & 6 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,45 @@
'use strict';
'use strict'
const {
Model
} = require('sequelize')
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
}, {});
User.associate = function(models) {
class User 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) {
User.hasMany(models.Reply, { foreignKey: 'UserId' })
User.hasMany(models.Tweet, { foreignKey: 'UserId' })
User.hasMany(models.Like, { foreignKey: 'UserId' })

User.belongsToMany(User, {
through: models.Followship,
foreignKey: 'followingId',
as: 'Followers'
})
User.belongsToMany(User, {
through: models.Followship,
foreignKey: 'followerId',
as: 'Followings'
})
}
};
return User;
};
User.init({
account: DataTypes.STRING,
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
introduction: DataTypes.TEXT,
avatar: DataTypes.STRING,
background: DataTypes.STRING,
role: DataTypes.STRING
}, {
sequelize,
modelName: 'User',
tableName: 'Users'
// underscored: true
})
return User
}
Loading