How to integrate Web MIDI API with React frontend and Django backend - javascript

I'm fairly new to Django and React but have a good grasp of Python and JavaScript.
What I'm trying to do is use the Web MIDI API to monitor some MIDI data, extrapolate some information from it and store that in a database. It's basically for a DAW, Software synth monitoring system, information can be transmitted as MIDI to the browser (via IAC) and then various pieces of information stored in the database. This needs to be done per user, with user data separation. I'm guessing I would need to implement a CRUD API. I currently have a Python project that does this and holds the data in memory formatted as JSON - the plan is to take this and turn it in to a Web App.
I've watched and followed a bunch of tutorials on integrating Django & React and also found this boilerplate for a basic login system.
https://github.com/justdjango/django-react-boilerplate
If possible I'd like to use this and just add in the functionality I need, can anyone point me in the right direction of where to start and where I would add the additional code for the MIDI stuff to this boilerplate.
There is another stage to this project but my aim is to tackle this step first and hopefully I'll gain a better understanding from there.
I've looked at this question:
django: keep each users data separate

I found the best way of integrating it after a bit of trial and error, so I'll answer it here for anyone else looking to do this kind of thing.
I've used a midi.js script with all the Web MIDI logic contained.
At the moment it just looks like this:
export default function () {
navigator.requestMIDIAccess().then(onMIDISuccess);
function onMIDISuccess(midiAccess) {
for (var input of midiAccess.inputs.values())
input.onmidimessage = getMIDIMessage;
}
}
function getMIDIMessage(msg) {
console.log(msg.data);
}
Then I've used a react component that renders nothing but imports and calls this midi logic from within the hook componentDidMount(). THIS was the key part that was missing and what makes it work. I've read a bit about it and it's to do with the lifecycle of the App.
That looks like this:
import { Component } from "react";
import midi from "./midi";
class ReceiveMIDI extends Component {
componentDidMount() {
midi();
}
render() {
return null;
}
}
export default ReceiveMIDI;
So far this is working for just logging the data to the console, I've already got a scaffold App set up and I'm now just writing a function to turn the MIDI into a post request to store the data in the database.

Related

Distributable/Distributed Web App with VueJS

I need to build a distributable app using VueJS. I'll describe the scene, so that it can be understood better.
Immagine the following:
Four companies have the same products database
Each of them has it's own politics, prices, custom colors, parameters, all of which are also stored in that database
These 4 companies want to integrate into their relative websites a page which shows their own catalogue (with their custom prices and politics and whatever), as well as, when you click on some of the products, the related information about that product
The question is: how can I make such an app using VueJS? Write it once and distribute it to these 4 different company websites?
And I've started to answer to my question doing the following:
I created an API which can be accessed by API Keys
Assigned to each company its very own API Key, so that requests coming with that API Key are associated with the given company
I created an app using VueCLI (which uses vue-router, for the pages/views, and axios for the API calls as well), wrote all my logic and components and styles and whatever else...and for development purposes I tried to use one of the 4 API keys (hard coding it into the axios.defaults.headers) to see if it all works...and it does!
Now, here comes the problem: I need to build/export the app in such a way that I can do something like this:
In www.company1.com/catalogue
Call catalogue.js and pass it the company1 API key
In www.company2.com/catalogue
Call catalogue.js and pass it the company2 API key
In www.company3.com/catalogue
Call catalogue.js and pass it the company3 API key
... I'll omit the company4 cause i'm sure you already got me.
Obviously I could export 4 different versions with the hard coded 4 different API's...but seems like a pretty stupid idea to me! Also, it exposes my client a lot cause, well, everybody could link to some of the companies' catalogue.js and, without configuration or whatever, visualise on it's own website my clients products..(which is obviously a problem).
I would like to have:
ONLY ONE catalogue.js file with some exposed parameters, as, for example: the API Key needed to identify the company.
In this way, everybody could still use that catalogue.js file, but with wrong credentials, it wouldn't produce a thing (i.e. will get an API error of unrecognized API key).
How on earth am I supposed to do this?
I'm banging my head on the wall from 2 weeks.
I've tried to export the app as Library, get errors like: Unknown custom element: <router-link> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I tried to export the app as Web Component...got same error and others as well.
Please help me understand where I go wrong, and how should I approach the problem.
Look into Vue Environment Variables https://cli.vuejs.org/guide/mode-and-env.html
Or you can make independent settings.json file and load it through the axios

Does ReactJS create the .js file for the web too?

I've never used react js and I have only dabbled with node's 'hello world' program.
I'm wondering if react works in such a way that if, say you add an <input type="text" /> tag, when you submit the form will react automatically handle the return of the data or do you need to separately write a client side .js file to handle the ajax data send to server?
Bonus: What is that type of framework called where it creates the two-way interaction automatically?
Apologies for what may be perceived as a basic question, but my beginner level comprehension of javascript hasn't completely got to grips with understanding what the docs actually mean.
Nope -- React is just a framework.
If you want to build a 'consolidated' javascript file that contains everything you need for your website, take a look at tools like webpack (or even better: create-react-app)
Form data is is submitted depending on how you structure your form, and that process is dictated a bit by HTML and a bit by your custom javascript.
To send AJAX based data, take a look at the 'fetch' API.
To manage the interaction between React, the data you're rendering, and other systems (like your server) take a look at Flux or Redux.
It really depend on how you write your application. React framework just render the "View" of your application.
Is you use a basical <form></form> with action the browser will automatically send the data into the "action" url attribute.
But you can just simulate a send of your form into a service/server/fake treatment and manage your return statement.
Well I never used React but, it's a javascript framework that has the same basic structure that Angular and Vue. Well REACT has directives that you can handle the data to send from the view into the component.js. If you want to send data to server you need to use libraries like 'axios' that you can import into you component and use it.

How to Setup Local Store with Static Data in Relay Modern

I'm building a React app that fetches data from a server and also passes static data to various components based on a user's selection from a dropdown menu. I'd like to use Relay Modern, but I've been unable to find anything in the docs about whether it supports manually loading static data to the store. Anyone know if this is possible/how to implement?
btw, I've seen a few similar questions about this here and elsewhere. But, it appeared that those pertained to Relay Classic rather than Relay Modern, which implemented massive changes.
I have have asked myself the same question. There must be a way to hydrate the Store/RecordSource. As a workaround I have been doing something like this. I create a query for the data that I want to add to the store and call commitPayload.
import {
createOperationSelector,
getOperation
} from 'relay-runtime';
const query = graphql `{ viewer { name } }`;
const environment = new Environment(...);
environment.commitPayload(createOperationSelector(getOperation(query)), {
viewer: {
name: 'Me'
}
});
Wondering if anyone from the relay team has some insight?

Electron database handling

I am trying to write a small app with Electron that needs a database. Currently I'm testing PouchDB, but that shouldn't really matter.
For better code quality I created a class that is going to handle the common database requests - it should be the only way to access the db.
Not sure, if I understood the main/renderer process concept correctly, but I think the main process should take care about db access. So this is my current configuration:
main.js
import Database from './database'
export const myDB = new Database()
database.js (obviously only a stub)
export default class Database {
hello = () => {
console.log("Hello World")
}
}
Root.js (one of the ui components [using react])
const remote = require('electron').remote
const main = remote.require('./main.js')
...
<button onClick={() => main.myDB.hello()}>Test</button>
My question: Is this a feasible solution for code structuring or am I getting something completely wrong? My JS experiences are just using some jQuery effects and Node experience is missing completely. This is just a small hobby project, so I just wanted to start coding ;)
You have it at the right end, the database related code should be executed in the main process.
main.js is what would be the main process, but it seems to be missing the code that creates a browser window (which in turn creates the renderer process). Take a look at the example of Electron here, the magic happens at createWindow().
Root.js is executed in the renderer process, it can only communicate with the main process through 'remote' or 'ipcRenderer' - the latter being a bit more secure. A bit more information about remote can be found on electron.rocks. You are doing it the right way, in terms of code structure.
The main process is responsible for creating and managing BrowserWindow instances and various application events. It can also do things like register global shortcuts, create native menus and dialogs, respond to auto-update events, and more. Your app’s entry point will point to a JavaScript file that will be executed in the main process. A subset of Electron APIs (see graphic below) are available in the main process, as well as all node.js modules. The docs state: “The basic rule is: if a module is GUI or low-level system related, then it should be only available in the main process.”
^Quoted from somewhere

Connecting a backbone localstorage based app to StackMob remote server via the Stackmob Sdk

I'm building which is a variation of this todos example
http://jasongiedymin.github.com/backbone-todojs-coffeescript/docs/coffeescript/todos.html
As you can see, the app saves the data to the browser's localstorage.
I want it to save it to the remote server I'm using, which is StackMob.
Having read the StackMob JS - SDK tutorial, it seems to tell me how to build an application from scratch based on the JS SDk
http://www.stackmob.com/devcenter/docs/JS-SDK-Tutorial
The question, is can I use what I already have written, and make it store the data at stackmob instead of the LocalStorage, Or I should better rewrite the app following the JS-SDK tutorial?
Thanks,
Oz
I'm not familiar with coffeescript syntax (at least, not yet!), but I'll familiarize myself with it in the near future. Unfortunately, the Local Storage adapter link in that Todo tutorial is broken, so I can't look into that, but in the meantime, maybe I can reason it out. I did notice that Todo is extending from Backbone.Model via the syntax, :
class Todo extends Backbone.Model
Non-coffeescript syntax would have it laid out as:
var Todo = Backbone.Model.extend({ ...});
Similarly, creating a Todo that saves to StackMob looks like:
var Todo = StackMob.Model.extend({...});
So perhaps this translation would work?
class Todo extends StackMob.Model
class TodoList extends StackMob.Collection
That seems like the coffeescript equivalent of defining a StackMob-enabled model, giving your model server-side CRUD abilities.
Models extending StackMob.Model will make an ajax call to StackMob with the JSON when calling save(), saving it to the server-side database. Similarly model.fetch() will retrieve from the database and populate the model.
TodoList would have StackMob queries built in so you can do something like:
(regular JS syntax:)
//Get the first five "done" Todo items, order by the "created date"
var q = (new StackMob.Collection.Query()).equals('done', true).
setRange(0,4).orderAsc('createddate');
var todos = new TodoList();
todos.query(q);
When I have more time, I will try that out myself later this week, but I wanted to get back to you now despite it being late tonight in case this can help get you going. Don't forget, for those to actually save properly, you'll need a StackMob account and initialize the JS SDK properly. But, the initialization steps are documented in the Getting Started: The JS SDK and the JS SDK Tutorial docs.
Hope this gets you on your way!
Erick

Categories