Backend ZH helper
Linkek
Package install guide
# Sequalize
$ npm install sequelize sequelize-cli
# Feathers
$ npm install @feathersjs/feathers @feathersjs/cli
# sqlite3
$ npm install sqlite3
# Apollo server*
$ npm install apollo-server
# Axios
$ npm install axios
# Nodemon
$ npm install --save-dev nodemon
Guides
Websocket server
server.js
const app = require('http').createServer(handler)
const io = require('socket.io')(app);
const fs = require('fs');
app.listen(8000);
function handler(req, res) {
const fileName = (req.url.includes(".js")) ? (__dirname + '/client.js') : (__dirname + '/index.html');
console.log(fileName);
fs.readFile(fileName,
(err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection',(socket) => {
console.log(`User with ${socket.id} has been connected.`);
socket.on('disconnect',(socket)=>{
console.log(`User with ${socket.id} has been disconnected.`);
});
});
client.js
const socket = io('http://localhost:8000');
socket.on(...)
index.html
<html>
<head>
<title>CLIENT</title>
</head>
<body>
<h1>Client</h1>
</body>
<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>
</html>
Apollo server & GraphQL
server.js
const { ApolloServer , gql } = require('apollo-server');
// const models = require('./models'); // for Sequalize
const axios = require('axios').default;
// Example axios fetch
const getItems = async (pageCap = 10000, page = 1) => {
const response = await axios.get(`https://diakkedvezmeny.com/items?pageCapacity=${pageCap}&page=${page}`);
return response.data.result;
}
const schema = gql`
type Query {
greeting(name: String): String
}
`
const resolvers = {
Query: {
greeting: (parent, {name}) => `Hello ${name}`,
}
}
async function run() {
// await models.sequelize.sync(); // optional
const server = new ApolloServer({
typeDefs: schema,
resolvers
// If you want db
// context: {
// tracks: models.Track,
// projects: models.Project,
// users: models.User,
// filters: models.Filter
// }
});
server.listen().then(r => console.log("OK Server is running"));
}
run();
Commandss
# Sequalize generate model
$ npx sequalize generate:model --name dogs --attributes name:string
# Feathers
$ npx feathers init
$ npx feathers generate service
# Sequalize
$ npx sequalize init
$ npx sequalize model:generate
$ npx sequelize migration:generate
Relationships
Sequalize
...
// eslint-disable-next-line no-unused-vars
dogs.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
dogs.belongsTo(models.users); // <-- Belongs to ONE user
dogs.hasMany(models.puppy); // <-- 1 Dog can have many puppy
dogs.belongsToMany(models.toys, {through: 'dogs_toys'}); // <-- Many to Many a dogs_toys táblával
};
return dogs;
...